Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring OpenSessionInViewInterceptor doesn't work

I had the (in)famous problem with hibernate and lazy loading when views are rendered.... As many say, the only two solutions are:

  • Make the method transactional (and this is not always desiderable)
  • Use OpenSessionInViewInterceptor.

The latter is preferable IMO. Anyway I'm not sure if this interceptor is firing at all (in fact I get the same Lazy loading exception and nothing changes):

org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: it.jsoftware.jacciseweb.beans.Listino.prodotti, no session or session was closed

I'm using simple annotation based url mappings, so reading the docs for Spring 3, I'm using this in my servlet-context.xml:

<bean id="handlerMapping"
        class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping">
        <!-- <property name="order" value="2" /> -->
        <property name="interceptors">
            <list>
                <ref bean="openSessionInViewInterceptorInst" />
            </list>
        </property>
    </bean>

Which should make the trick. But it is not working and I get the exception. How do I make sure my interceptor is firing? How do I solve this?

like image 920
gotch4 Avatar asked Feb 14 '11 13:02

gotch4


2 Answers

Are you using the @RequestMapping annotation? If I remember right there was an issue with putting the interceptor on the url bean. With Spring 3.0 you can define the interceptor like this:

<mvc:interceptors>
    <bean class="org.springframework.orm.hibernate3.support.OpenSessionInViewInterceptor">
        <property name="sessionFactory">
            <ref local="sessionFactory" />
        </property>
    </bean>
</mvc:interceptors>

assuming that sessionFactory is a reference to your SessionFactory bean.

You will also need to include the mvc namespace.

xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd"
like image 52
Robby Pond Avatar answered Oct 27 '22 22:10

Robby Pond


Try using <mvc:interceptors>.

By the way, @Transactional is a different thing - it doesn't make your collections work in the "view". It just opens a transaction (and a session) for the annotated method (and the methods it calls)

like image 37
Bozho Avatar answered Oct 27 '22 22:10

Bozho