ITPub博客

首页 > Linux操作系统 > Linux操作系统 > Hibernate 优化

Hibernate 优化

原创 Linux操作系统 作者:seablue_xj 时间:2008-05-10 19:17:57 0 删除 编辑

最好将batch size 设置为一个适当的值一般为30-50,在大量插入的时候停止一级缓存,
   否则有可能引起内存溢出,或者每组flush一次,之后清空即可。
        在批量更新,检索时注意使用游标ScrollableResults,可以很大的提高系统效率,如果
   直接使用session可能会造成内存的溢出。
   
     大量数据的插入:
 Transaction tx=null;
  Session session=null;
  session=HibernateSessionFactory.getSession();
  tx=session.beginTransaction();
  //String time1=new Date().toLocaleString();
  for(int i=0;i<100000;i++)
  {
   Customer customer=new Customer();
   customer.setUsername("zhang");
   customer.setPassword("zhang");
   if(i%20==0)
   {
    session.flush();
    session.clear();
   }
   session.save(customer);
   System.out.println(i);
  }
  tx.commit();
  //String time2=new Date().toLocaleString();
  session.close();

     批量更新:
           Session session = this.getSession();
  Transaction tx=session.beginTransaction();
  ScrollableResults customers = session.createQuery("select customer from Customer customer").setCacheMode(CacheMode.IGNORE)
    .scroll(ScrollMode.FORWARD_ONLY);
  int icount=0;
  while(customers.next())
  {
   Customer customer=(Customer)customers.get(0);
   customer.setUsername("zhang");
   System.out.println(icount);
   if(++icount%20==0)
   {
    session.flush();
    session.clear();
   }
  
   
  }
  
  tx.commit();
  session.close();


      批量更新:
      StatelessSession session=HibernateSessionFactory.getSessionFactory().openStatelessSession();
  Transaction tx=session.beginTransaction();
  
  ScrollableResults customers=session.getNamedQuery("findAll").scroll(ScrollMode.FORWARD_ONLY);
  int i=0;
  while(customers.next())
  {
   System.out.println(i++);
   Customer customer=new Customer();
   customer=(Customer) customers.get(0);
   customer.setPassword("zhang");
   session.update(customer);  //必须显示的调用update方法
  }
  tx.commit();
  session.close();

来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/7528999/viewspace-264919/ ,如需转载,请注明出处,否则将追究法律责任。

下一篇: J2EE持久层
请登录后发表评论 登录
全部评论

注册时间:2007-12-21

  • 博文量
    10
  • 访问量
    10912