Batch inserts with JPA/EJB3

Neither JPA nor Hibernate do provide particular support for batch inserts and the idiom for batch inserts with JPA would be the same as with Hibernate: EntityManager em = …; EntityTransaction tx = em.getTransaction(); tx.begin(); for ( int i=0; i<100000; i++ ) { Customer customer = new Customer(…..); em.persist(customer); if ( i % 20 == … Read more

Java: Insert multiple rows into MySQL with PreparedStatement

You can create a batch by PreparedStatement#addBatch() and execute it by PreparedStatement#executeBatch(). Here’s a kickoff example: public void save(List<Entity> entities) throws SQLException { try ( Connection connection = database.getConnection(); PreparedStatement statement = connection.prepareStatement(SQL_INSERT); ) { int i = 0; for (Entity entity : entities) { statement.setString(1, entity.getSomeProperty()); // … statement.addBatch(); i++; if (i % 1000 … Read more