April 11
getCurrentSession or openSession - a sessionic dilema
Posted by AjayOur hibernate code uses two different types of functions to access the session. openSession() and getCurrentSession(). But then I have always wondered the major difference between them. Now that I realized the difference, it is time to share it with the world.
First let’s talk about sessions in Hibernate.Session is defined as a unit of work. Work begins by starting a session and ends by closing a session.
A Transaction can also be defined similar to a session. But a transaction applies to databases. One kind of transaction works in auto commit mode, where there is one short transaction per SQL statement. Hibernate usually disables auto commit mode. A single Hibernate session has the same scope as a transaction. The most common model used is a session per request model where a single session/database transaction is executed for every request coming in from the client.

session per request
Multi step dialogs like wizards are implemented as session per conversation where a single session includes multiple transactions.

session per conversation
A session is opened whenever getCurrentSession() is called for the first time. This creates a brand new session if one does not exist or an existing one if one alrady exists. In tomcat this associates a session with a thread which is created using the underlying ThreadLocal object. But since Tomcat uses thread pooling it is entirely possible that a request may receive a thread with a session already associated with it, thus introducing the possibility of not even creating a brand new session. The method openSession() on the other hand creates a new session but does not attempt to associate it with a thread. But remember openSession() introduces another hitch in that it expects users to handle the closing and flushing of sessions themselves, instead of letting Hibernate do it automatically for us.
This is one of the advantage of using a JTA enabled container since JTA container will handle the session by binding it to a transaction instead of a thread like it happens in a Tomcat environment without JTA which essentially uses JDBC transactions.
References