zoukankan      html  css  js  c++  java
  • 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)

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

     
    方法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>
     
    

      

     
  • 相关阅读:
    后台管理界面
    登陆页面
    Django models中关于blank与null的补充说明
    django学习之路
    Django在根据models生成数据库表时报 __init__() missing 1 required positional argument: 'on_delete'
    django2笔记:路由path语法
    四 数据库备份
    Python操作MySQL
    三 数据库其他
    Shell----简单整理
  • 原文地址:https://www.cnblogs.com/zengda/p/4385490.html
Copyright © 2011-2022 走看看