13.2. 批量更新(Batch updates)

此方法同样适用于检索和更新数据。此外,在进行会返回很多行数据的查询时, 你需要使用 scroll() 方法以便充分利用服务器端游标所带来的好处。

  1. Session session = sessionFactory.openSession();
  2. Transaction tx = session.beginTransaction();
  3. ScrollableResults customers = session.getNamedQuery("GetCustomers")
  4. .setCacheMode(CacheMode.IGNORE)
  5. .scroll(ScrollMode.FORWARD_ONLY);
  6. int count=0;
  7. while ( customers.next() ) {
  8. Customer customer = (Customer) customers.get(0);
  9. customer.updateStuff(...);
  10. if ( ++count % 20 == 0 ) {
  11. //flush a batch of updates and release memory:
  12. session.flush();
  13. session.clear();
  14. }
  15. }
  16. tx.commit();
  17. session.close();