Best way to insert a good amount of records in hibernate

时光毁灭记忆、已成空白 提交于 2019-11-30 05:08:26

From *Java Persistence and Hibernate" (Manning) and following a comment from Pangea, use a stateless session (which doesn't have a persistence context cache) :

StatelessSession session = sessionFactory.openStatelessSession();
Transaction tx = session.beginTransaction();
for ( int i=0; i<100000; i++ ) {
    Item item = new Item(...);
    session.insert(item);
}
tx.commit();
session.close();
Qianyue

Just some corrections of the codes in the answer of Kartoch.

According to Batch Procession, "The insert(), update() and delete() operations defined by the StatelessSession interface are considered to be direct database row-level operations. They result in the immediate execution of a SQL INSERT, UPDATE or DELETE respectively. They have different semantics to the save(), saveOrUpdate() and delete() operations defined by the Session interface."

No more save(), flush(), clear() for StatelessSession. The code should be like this :

StatelessSession session = sessionFactory.openStatelessSession();
Transaction tx = session.beginTransaction();

for ( int i=0; i<100000; i++ ) {
  Item item = new Item(.....);
  session.insert(item );
}    

tx.commit();
session.close();

Finally, Here is a discussion of the difference between the normal batch inserting and the StatelessSession insert : Using StatelessSession for Batch processing.

Just open your session and transaction.

Add all elements in the save of the session.

Then commit the transaction.

//Remember to effective handler errors
public void saveAll(List<Object> list) throws Exception{
Session s = HibernateUtil.openSession();
Transaction tx = s.beginTransaction();
for(Object obj : list)
 s.save(obj);
tx.commit();
s.flush();
s.close();
}

Best is to use StatelessSessions. Consider the following example from (http://docs.jboss.org/hibernate/orm/3.3/reference/en-US/html/batch.html):

StatelessSession session = sessionFactory.openStatelessSession();
Transaction tx = session.beginTransaction();

ScrollableResults customers = session.getNamedQuery("GetCustomers")
    .scroll(ScrollMode.FORWARD_ONLY);
while ( customers.next() ) {
    Customer customer = (Customer) customers.get(0);
    customer.updateStuff(...);
    session.update(customer);
}

tx.commit();
session.close();

You can always get a Connection object directly in case you want to do the inserts outside of hibernate.

Connection connection = DB.getConnection();
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!