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();
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章