Difference between SessionFactory.openSession() and SessionFactory.getCurrentSession() in hibernate.

Both getCurrentSession() and openSession() are method of SessionFactory.

openSession() Method

  • It always creates a new Session object.
  • Programmer need to explicitly flush and close session objects.
  • openSession() is slower than getCurrentSession() in single threaded environment.
  • You do not need to configure any property to call this method.

getCurrentSession() Method

  • It creates a new Session iff there is no any session in current hibernate context.
  • Programmer do not need to flush and close session objects, it will be taken care by Hibernate internally.
  • In single threaded environment it is faster than openSession().
  • You need to configure additional property in hibernate.cfg.xml file <property name=”hibernate.current_session_context_class”>thread</property> otherwise it will throw an exception.

Leave a comment