Example & Tutorial understanding programming in easy ways.

Difference between getCurrentSession() and openSession() in Hibernate ?

Difference between getCurrentSession() and openSession() in Hibernate: 


getCurrentSession() :


In the "current session" refers to Hibernate Session bound by Hibernate behind the scenes, to the transaction scope. A Session is opened when getCurrentSession() is called for the first time and closed when the transaction ends. It is also flushed automatically before the transaction commits. You can call getCurrentSession() as often and anywhere you want as long as the transaction runs. 


To enable this strategy in your Hibernate configuration: 


set hibernate.transaction.manager_lookup_class to a lookup strategy for your JEE container 

set hibernate.transaction.factory_class to org.hibernate.transaction.JTATransactionFactory 


Only the Session that  obtained with sf.getCurrentSession() is flushed and closed automatically. 


Example : 


try { 

UserTransaction tx = (UserTransaction)new InitialContext().lookup("java:comp/UserTransaction"); 

tx.begin(); 


// Work to do

sf.getCurrentSession().createQuery(...); 

sf.getCurrentSession().persist(...); 

tx.commit(); 

catch (RuntimeException e) { 

tx.rollback(); 

throw e; // or display error message 


openSession() : 


If you decide to use manage the Session yourself the go for sf.openSession() , you have to flush() and close() it. 


It does not flush and close() automatically. 


Example : 


UserTransaction tx = (UserTransaction)new InitialContext().lookup("java:comp/UserTransaction"); 

Session session = factory.openSession(); 

try { 

tx.begin(); 


// Work to do

session.createQuery(...); 

session.persist(...); 

session.flush(); // Extra work you need to do 

tx.commit(); 

catch (RuntimeException e) { 

tx.rollback(); 

throw e; // or display error message 

finally { 

session.close(); // Extra work need to do 

}

Read More →