http://fuliang.iteye.com/blog/146965
我们在使用Hibernate的lazy load来优化性能的时候,只要Session关闭后再试图访问未被载入的对象时,就会出现异常。通常使用在事务之内来访问数据是适合的,但是有时候我们需要强制载入这些数据,例如在Web视图中访问这些模型对象。
在业务层强制载入这些数据,通常不是很好的解决方案,因为不同的视图在使用业务方法的时候,需要的数据通常不一样,这样业务方法可能绑定到特定的控制器中。在web.xml中配置:
<filter> <filter-name>OpenSessionInView</filter-name> <filter-class>org.springframework.orm.hibernate.support.OpenSessionInVewFilter</filter-class> <!--如果使用延迟关闭方式 <init-param> <param-name>singleSession</param-name> <param-value>false</param-value> </init-param> --> </filter> <filter-mapping> <filter-name>OpenSessionInView</filter-name> <url-pattern>*.do</url-pattern><!--以.do结束的的url为例--> </filter-mapping>
Spring Web MVC OpenSessionInViewInterceptor的配置:
<bean id="openSessionInView" class="org.springframework.orm.hibernate.support.OpenSessionInViewInterceptor"> <property name="sessionFactory"> <ref bean="sessionFactory"> </property> <!--如果使用延迟关闭方式 <property name="singleSession"> <value>false</value> </property> --> </bean> <bean id="myUrlMapping" class="org.springframeword.web.servlet.handler.SimpleUrlHandlerMapping"> <property name="interceptors"> <list> <ref bean="openSessionInView"> </list> </property> <property name="urlMap"> <!-- url mappings--> </property> </bean>