MDA/MDD/TDD/DDD/DDDDDDD
posts - 536, comments - 111, trackbacks - 0, articles - 0
  BlogJava :: 首页 :: 新随笔 :: 联系 :: 聚合  :: 管理

hibernate批量处理(转)

Posted on 2007-09-27 14:22 leekiang 阅读(1453) 评论(0)  编辑  收藏 所属分类: hibernate
在做大批量处理时,容易出现outofmemory的情况,分析及解决如下
(1)原因
 当首次作Insertupdatedeleteselect时,新产生的object在session关闭之前将自动装载到session级别的缓存区,如果,AP使用了二级缓存,同样也会装入到二级缓存。所以当数据量大时,就会出现outofmemory情况。
 
(2)解决方法
 
(A)批量插入(Batch inserts)/批量更新(Batch updates)
必须通过经常的调用 flush() 以及稍后调用 clear() 来控制第一级缓存的大小
如:
Session session = sessionFactory.openSession();
Transaction tx = session.beginTransaction();
  
for ( int i=0; i<100000; i++ ) {
    Customer customer = new Customer(.....);
    session.save(customer);
    if ( i % 20 == 0 ) {
//20, same as the JDBC batch size //20,与JDBC批量设置相同
        //flush a batch of inserts and release memory:
        //将本批插入的对象立即写入数据库并释放内存
        session.flush();
        session.clear();
    }
}
  
tx.commit();
session.close();
 
(B)大批量更新/删除(Bulk update/delete)
使用HQL语言
 
Session session = sessionFactory.openSession();
        Transaction tx = session.beginTransaction();

        String hqlUpdate = "update Customer set name = :newName where name = :oldName";
        int updatedEntities = s.createQuery( hqlUpdate )
                            .setString( "newName", newName )
                            .setString( "oldName", oldName )
                            .executeUpdate();
        tx.commit();
        session.close();

执行一个HQL DELETE,同样使用 Query.executeUpdate() 方法 (此方法是为 那些熟悉JDBC PreparedStatement.executeUpdate() 的人们而设定的)
Session session = sessionFactory.openSession();
        Transaction tx = session.beginTransaction();

        String hqlDelete = "delete Customer where name = :oldName";
        int deletedEntities = s.createQuery( hqlDelete )
                            .setString( "oldName", oldName )
                            .executeUpdate();
        tx.commit();
        session.close();

只有注册用户登录后才能发表评论。


网站导航: