1

i have a list of objects i just want to save that objects using hibernate batch processing .below is the code that i have tried

public void create(List<TransArchive> transArchives) {
Session session = getCurrentSession();
      Transaction tx = null;
      tx = session.beginTransaction();
          for (TransArchive transArchive : transArchives) {
              session.save(transArchive);
              } }

please help me to how to use batch processing in above code

jeb
  • 78,592
  • 17
  • 171
  • 225
ANucool Mittal
  • 205
  • 4
  • 13
  • Possible duplicate of [Spring Data JPA: Batch insert for nested entities](http://stackoverflow.com/questions/35791383/spring-data-jpa-batch-insert-for-nested-entities) – Dragan Bozanovic Sep 13 '16 at 14:55

1 Answers1

0

For hibernate batch processing you have to set the Batch_Size property in your configuration file.

<property name="hibernate.jdbc.batch_size"> 50 </property>

Later on, update your code as below:

public void create(List<TransArchive> transArchives) {
  Session session = getCurrentSession();
  Transaction tx = null;
  tx = session.beginTransaction();
      for (int i=0;i<transArchives.size();i++) {
          //save the object
          session.save(transArchives.get(i));
          if( i % 50 == 0 ) // Same as the JDBC batch size
          { 
           //flush a batch of inserts and release memory:
           session.flush();
           session.clear();
          }
      } 
  tx.commit();
  session.close();
}

This is Because by default, Hibernate will cache all the persisted objects in the session-level cache and ultimately your application would fall over with an OutOfMemoryException.

Rohit Gaikwad
  • 3,677
  • 3
  • 17
  • 40