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

6 篇文章 0 订阅
2 篇文章 0 订阅

转自:http://blog.sina.com.cn/s/blog_a5f093b40101el0l.html

    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.OpenSessionInViewInterce ptor,在appricationContext.xml 中设置

<bean name="openSessionInViewInterce ptor"
class="org.springframework.orm.hibernate4.support.OpenSessionInViewInterce ptor">
<property name="sessionFactory">
<ref bean="sessionFactory" />
</property>
</bean>
<bean id="urlMapping"
class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name="interceptors">
<list>
<ref bean="openSessionInViewInterce ptor" />
</list>
</property>
<property name="mappings">
<value>/*</value> <!-- 需要拦截的url -->
</property>
</bean>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值