码迷,mamicode.com
首页 > 编程语言 > 详细

spring 3.x + hibernate4.x 实现数据延迟加载

时间:2015-04-01 23:34:07      阅读:182      评论:0      收藏:0      [点我收藏+]

标签:

 

    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)

 解决方方法可以用过滤器也可以用拦截器

 
方法1: 利用org.springframework.orm.hibernate4.support.OpenSessionInViewFilter,在web.xml中配置 OperSessionInViewFilter.
   
 
<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>
 

  

 

spring 3.x + hibernate4.x 实现数据延迟加载

标签:

原文地址:http://www.cnblogs.com/zengda/p/4385490.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!