13.1. 批量插入(Batch inserts)

如果要将很多对象持久化,你必须通过经常的调用 flush() 以及稍后调用 clear() 来控制第一级缓存的大小。

  1. Session session = sessionFactory.openSession();
  2. Transaction tx = session.beginTransaction();
  3. for ( int i=0; i<100000; i++ ) {
  4. Customer customer = new Customer(.....);
  5. session.save(customer);
  6. if ( i % 20 == 0 ) { //20, same as the JDBC batch size //20,与JDBC批量设置相同
  7. //flush a batch of inserts and release memory:
  8. //将本批插入的对象立即写入数据库并释放内存
  9. session.flush();
  10. session.clear();
  11. }
  12. }
  13. tx.commit();
  14. session.close();