最好将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博客 ” ,链接:http://blog.itpub.net/7528999/viewspace-264919/,如需转载,请注明出处,否则将追究法律责任。
转载于:http://blog.itpub.net/7528999/viewspace-264919/