hibernate优化之批量处理

最好将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();
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值