views:

42

answers:

3

I am using Turbine 2.3.2 with Hibernate 3. My problem is that the Hibernate session is not active when my (Velocity 1.6.4) template is executed, and I am accessing data from the database for which Hibernate needs lazy initialization. Therefore I get a LazyInitializationException - no Session error.

Since I want my Hibernate session to be alive when a velocity template executes I would like to have a class to execute after and before the Velocity template. This way I could open and close my Hibernate session at one place. (Disabling lazy initialization in Hibernate is not an option for me). Are there any possibilities related or not to Turbine to write a kind of listener or a filter (I am not sure how to call it) that would execute right before and after a Velocity template has been executed? Or maybe the servlet container could filter requests .... What option would you recommend?

A: 

Try looking at the Spring OpenSessionInViewFilter. It opens the Hibernate Session and assigns it to a threadlocal. That way, you can pick it up in your data access layer and use it.

Kurt Du Bois
Thanks for the answer.
Atticus
A: 

Your question seems to be about the (in)famous Open Session In View (OSIV) pattern. Have a look at the Open Session in View page on the JBoss wiki, you'll find a filter based implementation (non Spring based).

Pascal Thivent
+1  A: 

Open Session in View is not a clean solution. You can configure in your criteria (if you use it) which association paths Hibernate has to eagerly fetch. If you use HQL, just "touch" the association while the session is still open.

Cid54
With this solution I would have to configure each object for which this problem appears. That would be a lot of objects, so I would not do this. I have already said that disabling lazy initialization (even if it would involve 'only' a few object) is not an option.
Atticus