延时加载问题解决OpenSessionInViewInterceptor 和 OpenSessionInViewFilter的配置

 在没有使用Spring提供的Open Session In View情况下,因需要在service(or Dao)层里把session关闭,所以lazy loading 为true的话,要在应用层内把关系集合都初始化,如 company.getEmployees(),否则Hibernate抛session already closed Exception;   

Open Session In View提供了一种简便的方法,较好地解决了lazy loading问题.    
    它有两种配置方式OpenSessionInViewInterceptor和OpenSessionInViewFilter(具体参看SpringSide),功能相同,只是一个在web.xml配置,另一个在application.xml配置而已。    
     Open Session In View在request把session绑定到当前thread期间一直保持hibernate session在open状态,使session在request的整个期间都可以使用,如在View层里PO也可以lazy loading数据,如 ${ company.employees }。当View 层逻辑完成后,才会通过Filter的doFilter方法或Interceptor的postHandle方法自动关闭session。

OpenSessionInViewInterceptor配置:

 

XML代码:

<beans> 3.<bean name="openSessionInViewInterceptor" class="org.springframework.orm.hibernate3.support.OpenSessionInViewInterceptor"> 4.<property name="sessionFactory"> 5.<ref bean="sessionFactory"/> 6.</property> 7.</bean> 8.<bean id="urlMapping" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping"> 9.<property name="interceptors"> 10.<list> 11.<ref bean="openSessionInViewInterceptor"/> 12.</list> 13.</property> 14.<property name="mappings"> 15.... 16.</property> 17.</bean> ... </beans>   

OpenSessionInViewFilter配置


XML代码:

<web-app> 3.... 4.<filter> 5.<filter-name>hibernateFilter</filter-name> 6.<filter-class> org.springframework.orm.hibernate3.support.OpenSessionInViewFilter </filter-class> 7.<!-- singleSession默认为true,若设为false则等于没用OpenSessionInView --> 8.<init-param> 9.<param-name>singleSession</param-name> 10.<param-value>true</param-value> 11.</init-param> 12.</filter> ... <filter-mapping> 13.<filter-name>hibernateFilter</filter-name> 14.<url-pattern>*.do</url-pattern> 15.</filter-mapping> ... </web-app>
 
 
 
 
 
 
 
 
 
 
 
 
 
 

你可能感兴趣的:(spring,Hibernate,exception,bean,session,Interceptor)