延時載入問題解決OpenSessionInViewInterceptor 和 OpenSessionInViewFilter的配置

來源:互聯網
上載者:User

在沒有使用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配置:

<beans>     

<bean name="openSessionInViewInterceptor" class="org.springframework.orm.hibernate3.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">     
....     
</property>     
</bean> ...
</beans> 

OpenSessionInViewFilter配置:

<web-app>     

  <filter>     
    <filter-name>hibernateFilter</filter-name>     
    <filter-class> org.springframework.orm.hibernate3.support.OpenSessionInViewFilter </filter-class>     

    <!-- singleSession預設為true,若設為false則等於沒用OpenSessionInView -->     
    <init-param>     
    <param-name>singleSession</param-name>     
    <param-value>true</param-value>     
    </init-param>     
   </filter> ...
   <filter-mapping>     
    <filter-name>hibernateFilter</filter-name>     
    <url-pattern>*.do</url-pattern>     
   </filter-mapping>
 ...
 </web-app>   


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.