Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Batch inserts with JPA/EJB3

Tags:

Does JPA/EJB3 framework provide standard way to do batch insert operation...? We use hibernate for persistence framework, So I can fall back to Hibernate Session and use combination session.save()/session.flush() achieve batch insert. But would like to know if EJB3 have a support for this...

like image 353
Raja Avatar asked Jan 15 '09 19:01

Raja


People also ask

Why does identity generation disable batch updates?

The only drawback is that we can't know the newly assigned value prior to executing the INSERT statement. This restriction is hindering the transactional write-behind flushing strategy adopted by Hibernate. For this reason, Hibernates disables the JDBC batch support for entities using the IDENTITY generator.

What is batch insert?

Batch inserts is the ability to send a set of inserts to a single table, once to the database as a single insert statement instead of individual statements. This method improves latency, and data insert times.

What is batch in JPA?

In this tutorial, we'll learn how we can batch insert and update entities using Hibernate/JPA. Batching allows us to send a group of SQL statements to the database in a single network call. This way, we can optimize the network and memory usage of our application.

What is JDBC batch insert?

Grouping a set of INSERT Statements and executing them at once is known as batch insert.


1 Answers

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 == 0 ) { //20, same as the JDBC batch size         //flush a batch of inserts and release memory:         em.flush();         em.clear();     } }  tx.commit(); session.close(); 

Using Hibernate's proprietary API in this case doesn't provide any advantage IMO.

References

  • JPA 1.0 Specification
    • Section 4.10 "Bulk Update and Delete Operations"
  • Hibernate Core reference guide
    • Chapter 13. Batch processing
like image 162
Pascal Thivent Avatar answered Oct 27 '22 15:10

Pascal Thivent