openSession and getCurrentSession Difference in Hibernate

When you get a session from the session factory object in hibernate, either you can use openSession or getCurrentSession. If you are using the openSession method, it opens a new session freshly. If you use getCurrentSession, it gets the current session from the existing thread context instead of opening a new session. You should have configured hibernate.current_session_context_class in the hibernate configuration file to use getCurrentSession method. The same entry looks like this:

<!--  Other elements goes here -->
<property name="hibernate.current_session_context_class">

If you are not adding the above configuration in your configuration file, you would get the following exception while getting the session.

Exception in thread "main" org.hibernate.HibernateException: No CurrentSessionContext configured!
	at org.hibernate.internal.SessionFactoryImpl.getCurrentSession(


import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.metamodel.MetadataSources;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;

public class HibernateUtil {
	public static void main (String args[]){
		Configuration configuration = new Configuration().configure();
		ServiceRegistry registry = new ServiceRegistryBuilder().configure().build();
		SessionFactory sessionFactory  = new MetadataSources(registry)
		Session session  = sessionFactory.getCurrentSession();
		//Session session  = sessionFactory.openSession();



About Krishna Srinivasan

He is Founder and Chief Editor of JavaBeat. He has more than 8+ years of experience on developing Web applications. He writes about Spring, DOJO, JSF, Hibernate and many other emerging technologies in this blog.

  • Gajraj Gupta

    Sir could you please tell which one to use when? Like what is the practical difference between both of these function. In almost all forums this is answer but the real use of these functions is yet not understandable to me.

    • Krishna Srinivasan

      You can use openSession it always work. If you have proper configuration to get the current context, use getCurrentSession