JDBC transactions with ThreadLocal

You can find the full source code in the example project DeploymentJdbc.

This configuration was used in most of the sample projects.

If we want to use a JDBC transaction factory, we don’t have to configure anything. It is the default behaviour. If you like you can define it explicitly in the Hibernate configuration file hibernate.cfg.xml

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

We can define a session context. This is a place where Hibernate will store the session. One option is a ThreadLocal session context. It uses a Java ThreadLocal which guaranties that every thread can only see its own session.

    <!--  thread is the short name for
      org.hibernate.context.ThreadLocalSessionContext
      and let Hibernate bind the session automatically to the thread
    -->
    <property name="current_session_context_class">thread</property>

In addition, the thread context of Hibernate will close the session automatically, if we call commit or rollback. In contrast to the default pattern, we need to call sessionFactory.getCurrentSession to pick a session from the context. If there is no session in the context, Hibernate will create one for us.

The Hibernate pattern is slightly shorter as we can omit the closing of the session:

SessionFactory factory = InitSessionFactory.getInstance();
Session session = factory.getCurrentSession();
Transaction tx = null;
try {
   tx = session.beginTransaction();
// alternativly:  factory.getCurrentSession().beginTransaction();
   // do some work
   tx.commit();
   } catch (RuntimeException e) {
      try {
         if (tx != null)
            tx.rollback();
      } catch (HibernateException e1) {
      log.error("Transaction roleback not succesful");
   }
   throw e;
}

Please be aware, that if you use factory.openSession, the session is not placed in the ThreadLocal context.

Hibernate in former times

In the old times you had to implement the ThreadLocal session context on your own. This is no longer required, at least if you are happy with the default contexts available.

But you will still find a lot of old examples in the web.