天天看点

org.hibernate.LazyInitializationException: could not initialize proxy - no Sessi

错误页面提示

could not initialize proxy - no Session

控制台

org.hibernate.LazyInitializationException: could not initialize proxy - no Session

病症:这是一个lazy使用后的Exception,使用迟时加载,在session(hibernate里的session),关闭后使用该对象的未加载变量,也就是说session已经关闭,没有保存到内存中,然后你使用了,导致该异常。

原因 :

      在hibernate中:hibernate3 默认支持延迟加载(lazy="proxy"我们可以把proxy看作是true),hibernate2 默认立即加载 (lazy="false")。

      在hibernate3中,所有的实体设置文件(user.hbm.xml)中的lazy属性都被默认设成了true,就是当这个类没有被调用时,延时加载,导致了以上情况的发生,在配置文件中将lzay属性设为false就可以了。

两种处理方法:

一、这是延时加载的问题,把有关联的所有pojo类,在hibernate.cfg.xml文件中。一般在many-to-one中,set标签内中设lazy="false" 。

二、用OpenSessionInViewFilter过滤器,注意hibernateFilter过滤器和struts2过滤器在映射时的先后顺序。同时要配置事物处理,否则会导致session处于只读状态而不能做修改、删除的动作。

即在web.xml文件中如下配置:

<!-- Spring ApplicationContext配置文件的加载目录。 -->
<context-param>
 <param-name>contextConfigLocation</param-name>
 <param-value>classpath*:spring/applicationContext.xml</param-value>
</context-param>      

 <!-- 解决延迟加载的问题 -->

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

 <!-- 继承Struts2的FilterDispatcher类,具备GBK等编码设定功能与struts2的action过滤功能。 -->

<filter>
 <filter-name>struts2</filter-name>
 <filter-class> com.iman.nrms.opm.web.common.FilterDispatcher
 </filter-class>
 <init-param>
  <param-name>encoding</param-name>
  <param-value>GBK</param-value>
 </init-param>
</filter>
<filter>
 <filter-name>struts-cleanup</filter-name>
 <filter-class> org.apache.struts2.dispatcher.ActionContextCleanUp
 </filter-class>
</filter>
<filter-mapping>
 <filter-name>hibernateFilter</filter-name>
 <url-pattern>/*</url-pattern>
</filter-mapping>
<filter-mapping>
 <filter-name>struts2</filter-name>
 <url-pattern>/*</url-pattern>
</filter-mapping>
<filter-mapping>
 <filter-name>struts-cleanup</filter-name>
 <url-pattern>/*</url-pattern>
</filter-mapping>