Wednesday, June 2, 2010

Cannot open connection Error on large hibernate updates/inserts

Problem:Recently I was getting "Cannot open connection/Transaction Inactive" Error when doing large number (100000) updates with hibernate
Session session = sessionFactory.openSession(); Transaction tx = session.beginTransaction(); for ( int i=0; i<;100000; i++ ) { Customer customer = new Customer(.....); session.save(customer); } tx.commit(); session.close();
Solution:When making new objects persistent flush() and then clear() the session regularly in order to control the size of the first-level cache.
Session session = sessionFactory.openSession(); Transaction tx = session.beginTransaction(); for ( int i=0; i<;100000; i++ ) { Customer customer = new Customer(.....); session.save(customer); if ( i % 20 == 0 ) { //similar to JDBC batch //flush a batch of inserts and release memory: session.flush(); session.clear(); } } tx.commit(); session.close();

No comments: