Hibernate 如何批量添加数据或批量插入数据呢?

Java-框架王 Hibernate 发布时间:2021-07-14 16:48:30 阅读数:15526 1
下文讲述Hibernate批量更新或插入数据的示例分享,如下所示: 实现思路:
 -----常规思路----
 Session session = SessionFactory.openSession();
Transaction tx = session.beginTransaction();
for ( int i=0; i<100000; i++ ) {
    Employee employee = new Employee(.....);
    session.save(employee);
}
tx.commit();
session.close();

/*
上面的写法,由于Hibernate缓存了会话层,所以可能会导致OutOfMemoryException,
那么我们需设置 hibernate.jdbc.batch_size 设置批处理的大小 如:80
*/


Session session = SessionFactory.openSession();
Transaction tx = session.beginTransaction();
for ( int i=0; i<100000; i++ ) {
    User  user = new User(.....);
    session.save(user);
    if( i % 80 == 0 ) { // Same as the JDBC batch size
        //flush a batch of inserts and release memory:
        session.flush();
        session.clear();
    }
}
tx.commit();
session.close();

/*
update 更新样例
*/

Session session = sessionFactory.openSession();
Transaction tx = session.beginTransaction();

ScrollableResults userCursor = session.createQuery("FROM User")
                                   .scroll();
int count = 0;

while ( userCursor.next() ) {
   User user = (User) userCursor.get(0);
   user.updateUser();
   seession.update(user); 
   if ( ++count % 80 == 0 ) {
      session.flush();
      session.clear();
   }
}
tx.commit();
session.close();

例:
 public void addUser( ){
      Session session = factory.openSession();
      Transaction tx = null;
      Integer employeeID = null;
      try{
         tx = session.beginTransaction();
        for ( int i=0; i<100000; i++ ) {
    User  user = new User(.....);
    session.save(user);
    if( i % 80 == 0 ) { // Same as the JDBC batch size
        //flush a batch of inserts and release memory:
        session.flush();
        session.clear();
    }
}
         tx.commit();
      }catch (HibernateException e) {
         if (tx!=null) tx.rollback();
         e.printStackTrace(); 
      }finally {
         session.close(); 
      }
      return ;
   }
}

版权声明

本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。

本文链接: https://www.Java265.com/JavaFramework/Hibernate/202107/495.html

最近发表

热门文章

好文推荐

Java265.com

https://www.java265.com

站长统计|粤ICP备14097017号-3

Powered By Java265.com信息维护小组

使用手机扫描二维码

关注我们看更多资讯

java爱好者