Hibernate openSession() vs getCurrentSession()
If we talk about SessionFactory.openSession()
- It always creates a new Session object.
- You need to explicitly flush and close session objects.
- In single threaded environment it is slower than getCurrentSession().
- You do not need to configure any property to call this method.
And If we talk about SessionFactory.getCurrentSession()
- It creates a new Session if not exists, else uses same session which is in current hibernate context.
- You do not need to flush and close session objects, it will be automatically taken care by Hibernate internally.
- In single threaded environment it is faster than openSession().
- You need to configure additional property. "hibernate.current_session_context_class" to call getCurrentSession() method, otherwise it will throw an exception.
As explained in this forum post, 1 and 2 are related. If you set hibernate.current_session_context_class
to thread and then implement something like a servlet filter that opens the session - then you can access that session anywhere else by using the SessionFactory.getCurrentSession()
.
SessionFactory.openSession()
always opens a new session that you have to close once you are done with the operations. SessionFactory.getCurrentSession()
returns a session bound to a context - you don't need to close this.
If you are using Spring or EJBs to manage transactions you can configure them to open / close sessions along with the transactions.
You should never use one session per web app
- session is not a thread safe object - cannot be shared by multiple threads. You should always use "one session per request" or "one session per transaction"