Hibernate/Spring: Session still closed before retrieval of child collection even with @Transactional on Service method

后端 未结 2 1817
梦如初夏
梦如初夏 2021-01-25 12:55

Hello Spring/Hibernate Gurus!

in a time like this i would like you to be my best friends.I am working on a project using hibernate 3.6.1.Final JPA implementation using s

相关标签:
2条回答
  • 2021-01-25 13:36

    The scope of the transaction (and hence the session) is only around the getContentsbyCategoryID() method. Once you return from it, the transaction is committed and the session is closed. Where, exactly, is it throwing the exception? Is it on the list() operation inside getContentsbyCategoryID()? Or is it, in fact, after you have returned from getContentsbyCategoryID() and trying to access the lazy collection somewhere else in the code? In that case, you either have to

    1. increase the scope of the transaction (and, hence, the session)
    2. change fetch-type to eager
    3. manually load the collection in getContentsbyCategoryID() (by calling size() on it, for instance)
    4. Adopt the open-session-in-view pattern (either through the OpenSessionInViewFilter or the OpenSessionInViewInterceptor)
    0 讨论(0)
  • 2021-01-25 13:52

    Does this happen when rendering the view? If it is the case you might want to consider using Spring's OpenSessionInViewFilter. This will bind the Session to the thread for the entire processing of the request. If using JPA you can use OpenEntityManagerInViewFilter.

    In your web.xml:

    <filter>
        <filter-name>OpenSessionInViewFilter</filter-name>
        <filter-class>org.springframework.orm.hibernate3.support.OpenSessionInViewFilter</filter-class>
        <init-param>
            <param-name>sessionFactoryBeanName</param-name>
            <param-value>sessionFactory</param-value>
        </init-param>
    </filter>
    
    <filter-mapping>
        <filter-name>OpenSessionInViewFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
    
    0 讨论(0)
提交回复
热议问题