Spring OpenSessionInView解析

來源:互聯網
上載者:User

OpenSessionInViewFilter是Spring提供的一個針對Hibernate的一個支援類,其主要意思是在發起一個頁面請求時開啟Hibernate的Session,一直保持這個Session,直到這個請求結束,具體是通過一個Filter來實現的。

由於Hibernate引入了Lazy Load特性,使得脫離Hibernate的Session周期的對象如果再想通過getter方法取到其關聯對象的值,Hibernate會拋出一個LazyLoad的Exception。所以為瞭解決這個問題,Spring引入了這個Filter,使得Hibernate的Session的生命週期變長。

 

對Hibernate的懶載入問題,Spring提供了OpenSessionInViewFilter和OpenSessionInViewInterceptor兩種東西。

 

  

1. Interceptor (beans.xml)

    <!-- =========== OpenSession In View pattern ==============-->
    <bean id="openSessionInViewInterceptor"
          class="org.springframework.orm.hibernate3.support.OpenSessionInViewInterceptor">
        <property name="sessionFactory" ref="sessionFactory"/>
    </bean>

    <bean id="urlMapping" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
        <property name="interceptors" ref="openSessionInViewInterceptor"/>
        <property name="mappings">
            <props>
            ......
            </props>
        </property>
    </bean>

2. Filter (web.xml)

<web-app>
 
<filter>
<filter-name>hibernateFilter</filter-name>
<filter-class>
org.springframework.orm.hibernate.support.OpenSessionInViewFilter
</filter-class>
</filter>
 
<filter-mapping>
<filter-name>hibernateFilter</filter-name>
<url-pattern>*.do</url-pattern>
</filter-mapping>

</web-app>

由於使用了OpenSessionInView模式後造成了記憶體和資料庫連接問題
這個問題是我在生產環境中碰到的一個問題。由於使用了OpenSessionInView模式,Session的生命週期變得非常長。雖然解決了Lazy Load的問題,但是帶來的問題就是Hibernate的一級緩衝,也就是Session層級的緩衝的生命週期會變得非常長,那麼如果你在你的Service層做大批量的資料操作時,其實這些資料會在緩衝中保留一份,這是非常耗費記憶體的。還有一個資料庫連接的問題,存在的原因在於由於資料庫的Connection是和Session綁在一起的,所以,Connection也會得不到及時的釋放。因而當系統出現業務非常繁忙,而計算量又非常大的時候,往往資料連線池的串連數會不夠。這個問題我至今非常頭痛,因為有很多客戶對資料連線池的數量會有限制,不會給你無限制的增加下去。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.