The morning after

Thursday, August 24, 2006

SessionFactory.getCurrentSession()

I recently refactored the data-access code in my current project. I noticed the Spring 2.0 Javadoc as well as the Hibernate 3.x Javadoc to recommend using SessionFactory.getCurrentSession() from now on.

For Spring users this means that extending HibernateDaoSupport should be avoided in favor of writing plain Hibernate code directly. When putting this in practice it feels like a natural evolution as there's no more need for the typical use of the callback mechanism in this approach.

A thing to note though, and I feel the current documentation does not stress this enough, is that this new approach requires a transactional context. Basically this means that a transaction interceptor must have been triggered prior to a call to SessionFactory.getCurrentSession(), otherwise a nasty exception will be thrown, saying no Hibernate session is bound to the current thread.
The documentation mentions this here.

What I did to make sure stuff would work as before is to intercept DAOs with both the HibernateInterceptor and a TransactionInterceptor, for the transaction interceptor I am using TransactionAspectSupport
which is able to detect transaction demarcation using Java5 annotations. This is nice since no further Spring configuration is required, just demarcate transactions on the DAOs and you're done.

All DAO methods are required to propagate the transaction (in order to make sure there is one, we need this to guarantee a reference to the current context in the session factory), finders are flagged with readOnly.

This all looks pretty innocent but I bothered to write this down here nevertheless, I've spent several hours figuring out what was going wrong, just to learn the Javadoc documentation wasn't mentioning any of this. My problems started when unit tests were failing because I was testing my DAOs (handwritten DAOs, not generated by AndroMDA) and I didn't have any transactional context at that point.

0 Comments:

Post a Comment

<< Home