Spring配置之OpenSessionInViewFilter


 

參考: 
OpenSessionInViewFilter作用及配置:http://www.yybean.com/opensessioninviewfilter-role-and-configuration 
http://blog.csdn.net/fooe84/article/details/680449 

主要涉及類: 
org.springframework.orm.hibernate3.support.OpenSessionInViewFilter 
org.springframework.orm.hibernate3.support.OpenSessionInViewInterceptor 

一、作用 
    說明一下Open Session in View的作用,就是允許在每次的整個request的過程中使用同一個hibernate session,可以在這個request任何時期lazy loading數據。 
如果是singleSession=false的話,就不會在每次的整個request的過程中使用同一個hibernate session,而是每個數據訪問都會產生各自的seesion,等於沒有Open Session in View. 
OpenSessionInViewFilter默認是不會對session 進行flush的,並且flush mode 是 never 

spring的OpenSessionInViewFilter過濾器,主要是為了實現Hibernate的延遲加載功能,基於一個請求一個hibernate session的原則。 

二、配置 
它有兩種配置方式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。 
1,web.xml配置OpenSessionInViewFilter 

Xml代碼  
<!--Hibernate Open Session in View Filte-->  
<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>/*</url-pattern>  
</filter-mapping>  

 


2,applicationContext.xml配置openSessionInViewInterceptor 

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


三、注意 
盡 管Open Session In View看起來還不錯,其實副作用不少。看回上面OpenSessionInViewFilter的doFilterInternal方法代碼,這個方法實際上是被父類的doFilter調用的,因此,我們可以大約了解的OpenSessionInViewFilter調用流程: 

request(請求)->open session並開始transaction->controller->View(Jsp)->結束transaction並 close session. 

一切看起來很正確,尤其是在本地開發測試的時候沒出現問題,但試想下如果流程中的某一步被阻塞的話,那在這期間connection就一直被占用而不釋放。最有可能被阻塞的就是在寫Jsp這步,一方面可能是頁面內容大,response.write的時間長,另一方面可能是網速慢,服務器與用戶間傳輸時間久。當大量這樣的情況出現時,就有連接池連接不足,造成頁面假死現象。 

Open Session In View是個雙刃劍,放在公網上內容多流量大的網站請慎用 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM