2016-09-13 65 views
1

我有对象,我只是想保存使用Hibernate对象的批量处理。下面是我曾尝试如何使用Hibernate批处理

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

请帮我如何使用批处理代码列表处理上面的代码

+0

[Spring Data JPA:嵌套实体的批插入]可能的重复(http://stackoverflow.com/questions/35791383/spring-data-jpa-batch-insert-for-nested-entities) –

回答

0

对于休眠批处理,您必须在您的配置文件中设置Batch_Size属性。

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

后来,如下更新代码:

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(); 
} 

这是因为默认情况下,Hibernate会缓存所有的持久化对象的会话级缓存,并最终你的应用程序将下降与OutOfMemoryException