OpenSessionInView模式

来源:互联网 发布:网络寻找客户资源方法 编辑:程序博客网 时间:2024/06/03 01:07



OpenSessionInView是用来支持Hibernate的Lazy Load特性的

就是在一个requestq请求内 一直保持这个Session
这样我们在页面中也可以取到延迟加的数据了
开始在web.xml中配置了
 <context-param>
  <param-name>contextConfigLocation</param-name>
  <param-value>classpath*:applicationContext.xml</param-value>
 </context-param>
 <listener>
  <listener-class>
   org.springframework.web.context.ContextLoaderListener
  </listener-class>
 </listener>
 <filter>
  <filter-name>openSessionInViewFilter</filter-name>
  <filter-class>
   org.springframework.orm.hibernate3.support.OpenSessionInViewFilter
  </filter-class>
 </filter>
 <filter-mapping>
  <filter-name>openSessionInViewFilter</filter-name>
  <url-pattern>/*</url-pattern>
 </filter-mapping>
但是运行的时候还是报错 org.hibernate.LazyInitializationException: could not initialize a role no session or session is closed。。。。把OpenSessionInViewFilter的源码看了几遍又查看log4.j日志发现hibernate session 提前关闭了 这个session并没有绑定在我的OpenSessionInViewFilter中
就是说我的web容器WebApplicationContext中的session 和hibernate的DAO对象中使用的session不是同一个
我在查询的时候是  
AbstractApplicationContext ctx = new ClassPathXmlApplicationContext(
    "applicationContext.xml");
  TbIndexDutyTypeDAO adao = (TbIndexDutyTypeDAO) ctx
    .getBean("tbIndexDutyTypeDAO");
  ctx.close();
这样来实例化dao对象的,问题就在这,这样实例化的dao对象中又开了一个session,
并不是OpenSessionInViewFilter的Session,没法只有大改,重新写applicationContext.xml
把所有dao对象改为用set方法来注入,把他们交给保存在web容器中的Spring配置信息来管理
终于在jsp页面中取到了hiberante 延迟加载的对象 
郁闷了我好几天哦~~~
现在终于可以流畅的使用OpenSessionViewFilter了

再也不用手动把Lazy改成false的烂方法了



转载注明出处

http://blog.csdn.net/xugangjava


原创粉丝点击