关于ssh开发中的no session问题

来源:互联网 发布:网络报纸 编辑:程序博客网 时间:2024/06/06 19:41
在ssh开发中,在dao层采用延时加载的查询方法,如果使用将hibernate托管给spring执行查询,在业务层开启事务,将查询的结果直接传递到页面,会报出no session 异常。
这是因为延时加载时,session查询到的是一个代理对象,只有id。当我们要使用查询内容的时候,会重新调用session查询。

但是在我们将该代理对象传递到页面之前,session就已经关闭了,当我们调用代理对象时,需要通过session重新查找,但是此时session无法获取到了。

异常信息如下:

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

解决方案:

在web.xml中配置延长session存活时间的过滤器OpenSession

<filter>
      <filter-name>OpenSession</filter-name>
      <filter-class>org.springframework.orm.hibernate5.support.OpenSessionInViewFilter</filter-class>
  </filter>
  <filter-mapping>
      <filter-name>OpenSession</filter-name>
      <url-pattern>/*</url-pattern>
</filter-mapping>