spring 3.x + hibernate4.x 实现数据延迟加载
Spring为我们解决Hibernate的Session的关闭与开启问题。
Hibernate 允许对关联对象、属性进行延迟加载,但是必须保证延迟加载的操作限于同一个 Hibernate Session 范围之内进行。如果 Service 层返回一个启用了延迟加载功能的领域对象给 Web 层,当 Web 层访问到那些需要延迟加载的数据时,由于加载领域对象的 Hibernate Session 已经关闭,这些导致延迟加载数据的访问异常
(eg: org.hibernate.LazyInitializationException:(LazyInitializationException.java:42)
- failed to lazily initialize a collection of role: cn.easyjava.bean.product.ProductType.childtypes, no session or session was closed
org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: cn.easyjava.bean.product.ProductType.childtypes, no session or session was closed)
解决方方法可以用过滤器也可以用拦截器
<filter> <filter-name>openSessionInViewFilter</filter-name> <filter-class>org.springframework.orm.hibernate4.support.OpenSessionInViewFilter </filter-class> <init-param> <param-name>sessionFactoryBeanName</param-name> <param-value>sessionFactory</param-value> </init-param> </filter> <filter-mapping> <filter-name>openSessionInViewFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> 注意:sessionFactiory 是自己在springContext中定义的 org.springframework.orm.hibernate4.LocalSessionFactoryBean的实例(一般在appricationContext.xml中定义) 方法二:利用org.springframework.orm.hibernate4.support.OpenSessionInViewInterceptor,在appricationContext.xml 中设置 <bean name="openSessionInViewInterceptor" class="org.springframework.orm.hibernate4.support.OpenSessionInViewInterceptor"> <property name="sessionFactory"> <ref bean="sessionFactory" /> </property> </bean> <bean id="urlMapping" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping"> <property name="interceptors"> <list> <ref bean="openSessionInViewInterceptor" /> </list> </property> <property name="mappings"> <value>/*</value> <!-- 需要拦截的url --> </property> </bean>
posted on 2015-04-01 22:01 nevergiveupzeng 阅读(222) 评论(0) 编辑 收藏 举报