Hibernate 如何批量添加数据或批量插入数据呢?
下文讲述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 ; } }
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。