转载:http://www.verydemo.com/demo_c146_i30349.html
原文:http://java.ccidnet.com/art/3539/20070802/1164285_1.html
批量更新是指在一个事务中更新大批量数据,批量删除是指在一个事务中删除大批量数据。以下程序直接通过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; |