PDA

View Full Version : Question regarding transaction and session management in Northwind Application



myenterprize
07-04-2007, 11:26 AM
Apologies if this has been covered in some other post ... but I have gone through almost all the posts and could not get a clear answer!!!

I was looking at the tests in Northwind Sample with NHibernate module, as these are tests OpenSessionInView does not make sense, but where is session Manaagement code? Is it in transaction proxy and interceptor? If yes, how does HibernateTemplate know that there is already a transaction and session is already opened ? AFAIK HibernateTemplate code opens/closes session during each method call. That's why we don’t need to worry about session management when using HibernateTemplate.
Then there is another issue I have been thinking about, if a method in service layer invokes multiple DAO methods (which is almost certainly always the case) and DAO's are built using HibernateTemplate, would not each DAO method invocation result in open session/ close sessions? so if a service method calls 3 DAO methods, there will be 3 open sessions and 3 close sessions????????
So the question I think boils down to.... How does spring ensure only one open session /close session call per service method when DAO's use Hibernate Template and rely on its session management??

I must admit I prefer the easy route of asking somebody to explain something in 2 minutes, which might take me hours to go through the murky world called code.
Thanks

Mark Pollack
07-12-2007, 07:39 PM
Hi,

HibernateTemplate's Session property will check thread local storage for an NHibernateSession that has been bound to the thread. The session itself is placed in thread local storage by the HibernateTransactionManager when a transaction begin. The relationship in this case is then one session per transaction. The OSIV module (in single session mode) binds the session to the thread at the start of the request and removes it at the end of the request.

As such, if you call multiple DAOs within a transaction, they will all use the same session. If you enable debug logging you will see messages like, "
Opened new Session [" + newSession + "] for Hibernate transaction" and
"Found thread-bound Session [" + sessionHolder.Session +
"] for Hibernate transaction". Enabling the debug trace is a good way to see the flow. I've made a JIRA issue to add this to the documentation.

Hope this helps.

Cheers,
Mark