hibernate 批量处理

来源:互联网 发布:陈奕迅 孙楠 知乎 编辑:程序博客网 时间:2024/04/29 13:30
hibernate 批量处理
当首次作Insertupdatedeleteselect时,新产生的object在session关闭之前将自动装载到session级别的缓存区,如果,AP使用了二级缓存,同样也会装入到二级缓存。所以当数据量大时,就会出现outofmemory情况。
1.批理插入
    方式一:
        在hibernate.cfg.xml中设置批量尺寸
        <property name="hibernate.jdbc.batch_size">50</property>
        关闭二级缓存
        <property name="hibernate.cache.use_second_level_cache">false</property>
    Session session=SessionFactory.openSession();
    Transaction tx=session.beginTransaction();
    for(int i=0;i<1000;i++)
    {
        Customer customer=new Customer();
         session.save(customer);
    if(i%50==0)
        {
            session.flush();
            session.clear();
          }
     }
        tx.commit();
        session.close();

方式二:绕过hibernate,直接使用JDBC进行批量插入
        Session session=SessionFactory.openSession();
    Transaction tx=session.beginTransaction();
    Connection conn=session.connection();
    PreparedStatement stmt=conn.prepareStatement("insert into orders(orderno) values (?)");
    for(int i=0;i<1000;i++)
    {
        stmt.setString(1,"a"+i);
        stmt.addBatch();
    }
    stmt.executeBatch();
    ts.commit();
    session.close();
二、批量更新
    hibernate.cfg.xml中配置:
    <property name="hibernate.query.factory_class">org.hibernate.hql.ast.ASTQuetyTranslatorFacotry</property>
    如,批量更新所有顾客联系电话中的空格
 方式一:
   Session session=SessionFactory.openSession();
    Transaction tx=session.beginTransaction();
    Query query=session.createQuery("update Customer set phone=Trim(phone)");
    query.executeUpdate();
    tx.commit();
    session.close();
方式二:绕过hibernate,通过jdbc
    Session session=SessionFactory.openSession();
    Transaction tx=session.beginTransaction();
     Connection conn=session.connection();
    Statment stmt=conn.createSatement();
    stmt.executeUpdate("update Customer set phone=Trim(phone)");
    tx.commit();
    session.close();
三、批量删除
    hibernate.cfg.xml中配置:
    <property name="hibernate.query.factory_class">org.hibernate.hql.ast.ASTQuetyTranslatorFacotry</property>
    如,批量更删除所有ID小于5000的顾客
 方式一:
   Session session=SessionFactory.openSession();
    Transaction tx=session.beginTransaction();
    Query query=session.createQuery("delete Customer where id<5000");
    query.executeUpdate();
    tx.commit();
    session.close();
方式二:绕过hibernate,通过jdbc
    Session session=SessionFactory.openSession();
    Transaction tx=session.beginTransaction();
     Connection conn=session.connection();
    Statment stmt=conn.createSatement();
    stmt.executeUpdate("delete from Customer where id<5000");
    tx.commit();
    session.close();
原创粉丝点击