看到博友的文章写的很全面,长知识了 原文地址:http://blog.csdn.net/myfuturein/article/details/51153266
转载自:http://hellotommy.iteye.com/blog/809205
hibernate3.3.2+spring3.0.3+struts2.2.1
懒加载(Load On Demand)是一种独特而又强大的数据获取方法,它能够在用户滚动页面的时候自动获取更多的数据,而新得到的数据不会影响原有数据的显示,同时最大程度上减少服务器端的资源耗用。(百度说的)
通俗点,就是在找一个对象时不找出与他关联的对象,而是在需要相关联对象(或其属性)时才去数据库中找,也称之为延迟加载。
一般来讲,我们是在many-to-one 的many设置lazy=false,这是hibernate自身提供给我们的。
后来spring关起来session,我们可以换一种方式:OpenSessionInViewFilter
OpenSessionInViewFilter是Spring提供的一个针对Hibernate的一个支持类
一般我们可以这么在web.xml中直接配置
openSessionInViewFilter
org.springframework.orm.hibernate3.support.OpenSessionInViewFilter
openSessionInViewFilter
/*
这样就省去了很多麻烦,就不需要在每一个many地方设置lazy=false了
这个方法应该很流行,我也是网上找来的。但偏偏我就是新手,直接拿过来用,项目部署了N次都不起效果,真是郁闷。每次报错:org.hibernate.LazyInitializationException: could not initialize proxy - no Session。
很明显,session关闭了。悲剧
当时就崩溃,为什么网上都这么说,却总是错误呢。
知道今天我看到了这篇文章http://www.iteye.com/topic/32001
突然恍然大悟。
既然spring管起了sessionFactory,获得session必须也通过他才对呀,所以这部分的mapping 也应该放在struts2的mapping后面,经过这个类,然后执行真正的Action代码,最后根据情况将Hibernate的Session进行关闭。
下面是完整的web.xml:
struts2
org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter
org.springframework.web.context.ContextLoaderListener
contextConfigLocation
classpath:daoContext.xml,classpath:actionContext.xml,classpath:serviceContext.xml,classpath:applicationContext.xml
openSessionInViewFilter
org.springframework.orm.hibernate3.support.OpenSessionInViewFilter
openSessionInViewFilter
/*
struts2
*.action
index.jsp
ok,这样就省去在每个many配置lazy了。
感谢分享,收益匪浅!