批量更新是指在一个事务中更新大批量数据,批量删除是指在一个事务中删除大批量数据。以下程序直接通过Hibernate API批量更新CUSTOMERS表中年龄大于零的所有记录的AGE字段:tx = session.beginTransaction(); Iterator customers=session.find("from Customer c where c.age>0").iterator(); while(customers.hasNext()){ Customer customer=(Customer)customers.next(); customer.setAge(customer.getAge()+1); } tx.commit(); session.close();
如果CUSTOMERS表中有1万条年龄大于零的记录,那么Session的find()方法会一下子加载1万个Customer对象到内存。当执行tx.commit()方法时,会清理缓存,Hibernate执行1万条更新CUSTOMERS表的update语句: update CUSTOMERS set AGE=? …. where ID=i; update CUSTOMERS set AGE=? …. where ID=j; …… update CUSTOMERS set AGE=? …. where ID=k;
以上批量更新方式有两个缺点:
(1) 占用大量内存,必须把1万个Customer对象先加载到内存,然后一一更新它们。
(2) 执行的update语句的数目太多,每个update语句只能更新一个Customer对象,必须通过1万条update语句才能更新一万个Customer对象,频繁的访问数据库,会大大降低应用的性能。
为了迅速释放1万个Customer对象占用的内存,可以在更新每个Customer对象后,就调用Session的evict()方法立即释放它的内存:
tx = session.beginTransaction(); Iterator customers=session.find("from Customer c where c.age>0").iterator(); while(customers.hasNext()){ Customer customer=(Customer)customers.next(); customer.setAge(customer.getAge()+1); session.flush(); session.evict(customer); } tx.commit(); session.close();
(编辑:aniston)
|