Spring中使用getSession()與經過HibernateTemplate進行數據操做...

在 Spring+Hibernate的集成環境裏,若是DAO直接使用HibernateDaoSupport的getSession()方法獲取 session進行數據操做而沒有顯式地關閉該session,那麼程序表現爲:每一個session會打開一個connection,而且 connection會一直保持(由於沒有顯式地close).若是程序使用了c3p0鏈接池,則由於c3p0鏈接池默認最大鏈接數是15,程序會表現爲 當打開第15個鏈接時,程序處於停滯狀態,等待從鏈接池獲取新的鏈接.
  在一樣條件下,使用HibernateTemplate進行數據操做,就沒有鏈接數持續增加的狀況,程序結束時鏈接數歸零.這印證了spring文檔 上所說:HibernateTemplate會對session進行了管理,可以確保Session實例的正確打開和關閉.
  須要注意的是:在Spring環境裏,即便咱們使用Hibernate原生的API,好比這裏所說的使用HibernateDaoSupport的 getSession()方法獲得Session進行數據操做(而不是使用Spring本身提供的API,好比HibernateTemplate),這 些操做也依然會被歸入spring管理的事務中去.緣由是經過getSession()方法獲得Session是一個綁定到當前事務上的session. 此處可參考:http://www.javaeye.com/topic/110801.這就是爲何Spring文檔中提到的:You can implement DAOs based on the plain Hibernate 3 API, while still being able to participate in Spring-managed transactions.
     若是程序使用了OpenSessionInViewFilter或者OpenSessionInViewInterceptor那將是另一種情形了.

  簡單總結: HibernateDaoSupport的getSession()獲得的Session會參與Spring管理的事務中,可是不能自動的關閉. HibernateTemplate 除能參與到 Spring管理的事務中,還 可以確保Session實例的正確打開和關閉.java

web.xml配置web

<filter>
        <filter-name>hibernateOpenSessionInViewFilter</filter-name>
        <filter-class>org.springframework.orm.hibernate3.support.OpenSessionInViewFilter</filter-class>
         <init-param> 
          <param-name>flushMode</param-name> 
          <param-value>AUTO</param-value> 
       </init-param>
       <init-param> 
          <param-name>singleSession</param-name> 
           <param-value>true</param-value> 
      </init-param> 
    </filter>
    <filter-mapping>
        <filter-name>hibernateOpenSessionInViewFilter</filter-name>
        <url-pattern>*.do</url-pattern>
        <dispatcher>REQUEST</dispatcher>
    <dispatcher>FORWARD</dispatcher>
    </filter-mapping>
spring

相關文章
相關標籤/搜索