Saturday, 18 April 2020

Difference Between openSession() and getCurrentSession() Methods in Hibernate

         As we know, there are two ways to obtain a Session from the Hibernate SessionFactory: openSession() and getCurrentSession().

The openSession() method always creates and returns a new Session instance each time it is called. In contrast, the getCurrentSession() method returns the Session associated with the current context (such as the current thread or transaction). If no Session is available in the current context, Hibernate creates a new one and associates it with that context.

Let's explore a few more differences between openSession() and getCurrentSession().


openSession():-

  • The openSession() method creates a new Session instance every time it is called.

  • You must explicitly flush and close the Session after use.

  • In a single-threaded environment, openSession() is generally less efficient than getCurrentSession() because it creates a new Session for every call.

  • No additional Hibernate configuration is required to use the openSession() method.



getCurrentSession():-

  • The getCurrentSession() method returns the Session associated with the current Hibernate context. If no Session exists in the current context, Hibernate creates a new one and binds it to that context.

  • You do not need to explicitly flush or close the Session. When using transaction management, Hibernate automatically manages the session lifecycle.

  • In a single-threaded environment, getCurrentSession() is generally more efficient than openSession() because it reuses the context-bound Session instead of creating a new one for every request.

  • To use getCurrentSession(), you must configure the hibernate.current_session_context_class property (or use a framework such as Spring, which manages the current session automatically). Otherwise, calling getCurrentSession() may result in a HibernateException.


Thank you for visiting the blog.