Using Hibernate and Jdbc DAOs in the same Transaction

I think it is very hard to build any enterprise application without using at least a little bit of straight Jdbc. Even if an application uses Hibernate heavily, there will be situations where using straight Jdbc makes most sense.

We use HibernateDaoSupport (using GenericDAO pattern) and JdbcDaoSupport Spring classes as the base classes for the HibernateDAOs and JdbcDAOs respectively. 

Here are some of the things to be aware of when we mix these 2 techniques for the CRUD operations within the same transaction:

  • The HibernateDaoSupport beans and the JdbcSupportBeans should be wired with the same DataSource instance.
  • Use HibernateTransactionManager, which auto-detects the DataSource used by Hibernate and transparently uses Hibernate transactions as JDBC transactions for that DataSource (using ThreadLocal connections).
  • When using CMT or using declarative transactions using Spring AOP (Spring Transaction interceptors), the connections must be explicitly closed by the Jdbc DAOs. Otherwise, this leads to connection leaks. See Hibernate JavaDocs for Session.connection() method for more info. My favorite way to avoid this problem is to use Spring JdbcTemplate inside the Jdbc DAOs.
  • Explicit flush on the Hibernate session may be required wherever Jdbc calls need to read the updates made through the hibernate objects within the same transaction.
  • Explicit invalidation or refresh of the Hibernate Session is needed whenever updates are made through Jdbc.
  • Hibernate by default uses Optimistic locking. So, the retry logic needs to be implemented in appropriate places.

As you can see it can get very tricky to synchronize straight Jdbc and Hibernate updates. So, I would try to use straight Jdbc only for bulk reads and reads that require complex joins, if possible.

Technorati Tags: , ,

About Shashi Velur

I am Shashi Velur. I live in Austin, TX with my wife and daughter. I consider myself an experienced Enterprise Software Developer/Architect. The views expressed are mine alone and do not necessarily represent the views of my current and any of my previous employers.
This entry was posted in Hibernate and tagged , , . Bookmark the permalink.

Leave a Reply

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

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>