參考:
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
2,applicationContext.xml配置openSessionInViewInterceptor
三、注意
盡 管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是個雙刃劍,放在公網上內容多流量大的網站請慎用