Spring的OpenSessionInViewFilter和OpenSessionInViewInterceptor

http://frederick.javaeye.com/blog/108106

xml 代码
  对Hibernate的懒加载问题,Spring提供了OpenSessionInViewFilter和OpenSessionInViewInterceptor两种东西。

 

  对OpenSessionInViewFilter,需要在web.xml文件中配置。

xml 代码
<filter>  
  <description>处理Hibernate的懒加载问题description>  
  <filter-name>OpenSessionInViewFilterfilter-name>  
  <filter-class>  
    org.springframework.orm.hibernate3.support.OpenSessionInViewFilter   
  filter-class>  
  <init-param>  
    <description>  
       默认情况下,这个Filter会在Spring的bean池中找一个叫做sessionFactory的bean。如果使用了其他名字的SessionFactory,则应该在这里   
       指定这个名字。   
    description>  
    <param-name>sessionFactoryBeanNameparam-name>  
    <param-value>localSessionFactoryparam-value>  
  init-param>  
  <init-param>  
    <description>description>  
    <param-name>singleSessionparam-name>  
    <param-value>trueparam-value>  
  init-param>  
filter>  
<filter-mapping>  
  <filter-name>OpenSessionInViewFilterfilter-name>  
  <url-pattern>*.dourl-pattern>  
filter-mapping>  


         默认情况下,这个Filter会在Spring的bean池中找一个叫做sessionFactory的bean。如果使用了其他名字的SessionFactory,则应该在这里指定这个名字。

xml 代码
<init-param>  
  <description>  
     默认情况下,这个Filter会在Spring的bean池中找一个叫做sessionFactory的bean。如果使用了其他名字的SessionFactory,则应该在这里   
     指定这个名字。   
  </description>  
  <param-name>sessionFactoryBeanName</param-name>  
  <param-value>localSessionFactory</param-value>  
</init-param>  

    其中的sessionFactoryBeanName是你的SessionFactory的实例的名字。这个名字是你在Spring的Bean定义文件中声明的SessionFactory的实例的bean名字。默认这个Filter会使用“sessionFactory”这个值,如果你的SessionFactory确实是这个名字的话,可以不用指明它的名字。但是如果你向我一样,给SessionFactory使用了其他名字,就得在这里声明了。

对OpenSessionInViewInterceptor,就纯粹是Spring IOC容器管理的东西了。

    首先,你需要在Spring中声明一个OpenSessionInViewInterceptor的实例

xml 代码
<bean id="openSessionInViewInterceptor" class="org.springframework.orm.hibernate3.support.OpenSessionInViewInterceptor">  
  <property name="sessionFactory" ref="localSessionFactory" />  
</bean>  

    然后,你需要在bean urlMapping 中使用这个interceptor:

java 代码
<bean id="urlMapping" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">   
  <property name="interceptors">   
    <list>   
      <ref bean="openSessionInViewInterceptor" />   
    </list>   
  </property>   
  <property name="mappings">   
    <props>   
      <prop key="main.do">mainFrameController</prop>   
    </props>   
  </property>   
</bean>  

 

    在实际应用中,发现一个奇怪的现象,就是使用OpenSessionInViewFilter以后,发现竟然有时候懒加载会出错,因为时间紧迫,还没有找到原因是什么。但是在使用了OpenSessionInViewInterceptor以后,这个问题解决了。

    有空的时候再来看到底是什么原因。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值