In Hibernate 3.1 the default connection release mode changed from ON_CLOSE to auto. That means that the connection is closed after the end of the transaction (Connection Release Modes).
I am using Hibernate and the Spring transaction facility with a hand written interceptor, that does the following things:
I think this should be the right pattern for long conversations and Spring
check if a Hibernate Session is in the HttpSession.
if so reconnect and bind to the TransactionSyncronizationManager
if not, create a new Session, bind to the TransactionSyncronizationManager
and put it into the HttpSession
unbind the session from TransactionSyncronizationManager
if a special flag is set, close the session
else disconnect the session, but let it in the HttpSession
The problem is now the following: The servlet calls a business method, which is transactionally marked via the Spring transaction facility. It completes the method and commits, and therefore Hibernate 3.1 closes the connection. What now happens, is clear:
If a a lazy initialized object is accessed in the view rendering phase a LazyInitializationException is thrown.
So what can we do? Its possible to change the default connection release mode to ON_CLOSE, but this link and this link discourages it.
Another possibility is to start a transaction in my interceptor, when I open/reconnect the Session. But then database locks are kept during the view rendering phase, so this is also not a good idea.
The Hibernate page advises also to use two transactions (http://www.hibernate.org/43.html#A9). How can I accomplish this?
Any other suggestions?
I am not using the OpenSessionInView pattern, but I think it has the same problem. Is anybody using the OSIV pattern with Sping and Hibernate 3.1? If it is working with OSIV, whats the problem with my long conversation interceptor?