Difference between openSession and getCurrentSession in Hibernate

You might know there are two ways to create or get session in hibernate. We have below two methods in SessionFactory class to create a session.

Tutorial Content:

  • openSession
  • getCurrentSession
Now we will see differences between openSession and getCurrentSession.

openSession

When you call SessionFactory.openSession, it always create new Session object afresh and give it to you. You need to explicitly flush and close these session objects. As session objects are not thread safe, you need to create one session object per request in multithreaded environment and one session per request in web applications too.

getCurrentSession

When you call SessionFactory. getCurrentSession, it will provide you session object which is in hibernate context and managed by hibernate internally. It is bound to transaction scope.
When you call SessionFactory. getCurrentSession , it creates a new Session if not exists , else use same session which is in current hibernate context. It automatically flush and close session when transaction ends, so you do not need to do externally.
If you are using hibernate in single threaded environment , you can use getCurrentSession, as it is faster in performance as compare to creating  new session each time.
You need to add following property to hibernate.cfg.xml to use getCurrentSession method.
If you do not configure above property, you will get error as below.

openSession vs getCurrentSession :

Lets summarise differences between openSession and getCurrentSession in below table
Parameter
openSession
getCurrentSession
Session object
It always create new Session object
It creates a new Session if not exists , else use same session which is in current hibernate context
Flush and close
You need to explicitly flush and close session objects
You do not need to flush and close session objects, it will be automatically taken care by Hibernate internally
Performance
In single threaded environment , It is slower than getCurrentSession
In single threaded environment , It is faster than getOpenSession
Configuration
You do not need to configure any property to call this method
You need to configure additional property “hibernate.current_session_context_class” to call getCurrentSession method, otherwise it will throw exceptions.

Was this post helpful?

Leave a Reply

Your email address will not be published. Required fields are marked *