对Hibernate的懒加载问题,Spring提供了OpenSessionInViewFilter和OpenSessionInViewInterceptor两种东西。
对OpenSessionInViewFilter,需要在web.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,则应该在这里指定这个名字。
- <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的实例
- <bean id="openSessionInViewInterceptor" class="org.springframework.orm.hibernate3.support.OpenSessionInViewInterceptor">
- <property name="sessionFactory" ref="localSessionFactory" />
- </bean>
然后,你需要在bean urlMapping 中使用这个interceptor:
- <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以后,这个问题解决了。
有空的时候再来看到底是什么原因。