6.hibernate的批量更新

来源:互联网 发布:独立域名是什么 编辑:程序博客网 时间:2024/06/06 00:00
<pre name="code" class="html"><pre name="code" class="html">public class UserManager{public static void main(String[] args)throws Exception{UserManager mgr = new UserManager();mgr.updateUsers();HibernateUtil.sessionFactory.close();}private void updateUsers()throws Exception{//打开SessionSession session = HibernateUtil.currentSession();//开始事务Transaction tx = session.beginTransaction();ScrollableResults users = session.createQuery("from User")//HQL查询语句.setCacheMode(CacheMode.IGNORE)//禁止缓存.scroll(ScrollMode.FORWARD_ONLY);//设置只向前滚动int count=0;while(users.next()){//创建User实例User u1 = (User) users.get(0);u1.setName("新名字" + count);if(++count%20==0){session.flush();session.clear();}}//提交事务tx.commit();//关闭事务HibernateUtil.closeSession();}}配置文件注意创建表的配置为update而不是create不然会被清空<p><property name="hbm2ddl.auto">update</property></p>


                                             
0 0