Hibernate built-in Session Context Management

Starting with v3.1 (notice I work with 3.2.5ga though) Hibernate has introduced the interesting (and really helpful) concept of Session context management where Hibernate itself provides a built-in mechanism to manage the session.

In previous releases the session (and the transaction) had to be maintained by the developer, typically using the Thread Local pattern where the session is stored in a Java ThreadLocal class (more details here). Fortunately a much simpler way is provided by Hibernate v3.1.

How it works

Simply the developer retrieves the session calling getCurrentSession() method on the SessionFactory. It is the first invocation which actually opens the session (however you can only call beginTransaction() before using it ) and binds that with the current Java thread. All following invocations of the same method just return the same session.

An example:

try {

// access entities (this should in a DAO)
// commit transaction
catch (RuntimeException e) {
// handle exception
throw e;

Cool! Now we only need to use getCurrentSession() and just begin and end the transaction accordingly.

Configure Current Session Management

Extra settings are required to enable the mechanism, just add the following in the application hibernate.cfg.xml:

<property name="hibernate.transaction.factory_class">org.hibernate.transaction.JDBCTransactionFactory</property>
<property name="hibernate.current_session_context_class">thread</property>

Closing the Session

There is one important thing you need to be aware: the commit() and rollback() methods of the Transaction close automatically the session.

If you apply the Open Session in View pattern (recommended approach) using a filter and ensuring there is only one transaction per request then happy days! But if you need instead to open and close several transactions within the same request you need to look at “long conversations” and “managed” sessions (see below).

Flushing the Session

Another important detail: a session bound to the thread cannot be flushed as you please. If you need to control the session flushing (either via the FlushMode or manually) then again it is time for “managed” sessions.

Connection Release Mode

The release of the JDBC connection bound to the session cannot be controlled: in the case of the Session Context Management the JDBC connection is released when the session is closed (hibernate.connection.release_mode parameter is auto).


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: