Saturday, 18 April 2020

Difference between openSession and getCurrentSession methods in Hibernate

         As we know that there are two ways to create/get session in Hibernate. There are two methods openSession() and getCurrentSession() methods to create/get session object from SessionFactory class. The openSession() method always creates new session each time but getCurrentSession() method of sessionFactory returns the session object from context, if session is not present in the context then will create new session object.

We can see few more differences as below,

openSession():-

  • It will create new Session object each time when you call openSession() method.
  • You need to explicitly flush and close session objects.
  • In single threaded environment , It is slower than getCurrentSession() method.
  • No need to configure any property to call this method.


getCurrentSession():-

  • It creates a new Session if session doesn't exists , else it will use same session which is in current hibernate context.
  • No need to flush and close session objects, it will be automatically taken care by Hibernate internally.
  • In single threaded environment , it is faster than getOpenSession() method.
  • Need to configure additional property “hibernate.current_session_context_class” to call getCurrentSession() method, otherwise it will throw an exception.

Related Posts:--

No comments:

Post a Comment