failed to lazily initialize a collection of role:no session or session was close

解决方法(延迟加载问题)
把fetch= FetchType.LAZY 改成 fetch = FetchType.EAGER


1、OpenSessionInView模式:

以下有2种方法,第1种是结合SPRING,第2种是采用了拦截器

Spring+Hibernate中,     集合映射如果使用lazy="true", 当PO传到View层时, 出现未初始化session已关闭的错误,只能在dao先初始化

parent.getChilds().size();s

Spring提供Open Session In View来解决这个问题, 有两种方式
1. Interceptor
       <!--</span><span style="COLOR: rgb(0,128,0)"> =========== OpenSession In View pattern ==============</span><span style="COLOR: rgb(0,128,0)">-->
    <bean id="openSessionInViewInterceptor"
             class="org.springframework.orm.hibernate3.support.OpenSessionInViewInterceptor">
        <property name="sessionFactory" ref="sessionFactory"/>
    </bean>

    <bean id="urlMapping" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
        <property name="interceptors" ref="openSessionInViewInterceptor"/>
        <property name="mappings">
            <props>
               ......
            </props>
        </property>
    </bean>
2. Filter
<web-app>

<filter>
<filter-name>hibernateFilter</filter-name>
<filter-class>
org.springframework.orm.hibernate.support.OpenSessionInViewFilter
</filter-class>
</filter>

<filter-mapping>
<filter-name>hibernateFilter</filter-name>
<url-pattern>*.do</url-pattern>
</filter-mapping>

</web-app> 
第2种解决方法:

Hibernate.initialize()强制加载关联对象(initialize为延迟加载的集合)

你可能感兴趣的:(failed to lazily initialize a collection of role:no session or session was close)