OpenSessionInViewFilter 的配置及替代方案__OpenSessionInViewFil

來源:互聯網
上載者:User

註:OpenSessionInViewFilter模式可以解決session導致消極式載入問題,也會引入其他問題,例如session聲明周期變長、Connection串連資料庫時間變長等導致資料庫效能下降和應用伺服器緩衝緊張。


Spring 為我們提供了一個叫做 OpenSessionInViewFilter 的過濾器,他是標準的 Servlet Filter 所以我們把它按照規範配置到 web.xml 中方可使用。使用中我們必須配合使用 Spring 的 HibernateDaoSupport 來進行開發,也就是說,我們的dao層的類都要繼承於 HibernateDaoSupport,從中由 Spring 來控制 Hibernate 的 Session 在請求來的時候開啟,走的時候關閉,保證了我們訪問資料對象時的穩定性。

  1. 在 web.xml 中加入對應過濾器設定檔

  Java代碼   <!-- Spring的OpenSessionInView實現 -->   <filter>       <filter-name>openSessionInViewFilter</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>    <!--    指定org.springframework.orm.hibernate3.LocalSessionFactoryBean在spring設定檔中的名稱,預設值為sessionFactory。 如果LocalSessionFactoryBean在spring中的名稱不是sessionFactory,該參數一定要指定,否則會出現找不到sessionFactory的例外。所以預設可以不寫   -->    <init-param>        <param-name>sessionFactoryBean</param-name>      <param-value>sessionFactory</param-value>     </init-param>    </filter>   <filter-mapping>       <filter-name>openSessionInViewFilter</filter-name>       <url-pattern>/*</url-pattern>   </filter-mapping>    

 2. 在我們訪問持久層資料是使用 Spring 為我們的 HibernateDaoSupport 的支援,並使用其中的對應方法操作我們的持久層資料

  Java代碼   import org.springframework.orm.hibernate3.support.HibernateDaoSupport;      public class XxxDAO extends HibernateDaoSupport {          public void save(Xxx transientInstance) {           try {               getHibernateTemplate().save(transientInstance);           } catch (RuntimeException re) {               throw re;           }       }   }    

 

OpenSessionInViewFilter的主要功能是用來把一個Hibernate Session和一次完整的請求過程對應的線程相綁定。Open Session In View在request把session綁定到當前thread期間一直保持hibernate session在open狀態,使session在request的整個期間都可以使用,如在View層裡PO也可以lazy loading資料,如 ${ company.employees }。當View 層邏輯完成後,才會通過Filter的doFilter方法或Interceptor的postHandle方法自動關閉session。

  很多人在使用OpenSessionInView過程中提及一個錯誤:

org.springframework.dao.InvalidDataAccessApiUsageException: Write operations are not allowed in read-only mode (FlushMode.NEVER) – turn your Session into FlushMode.AUTO or remove ‘readOnly’ marker from transaction definition

  看看OpenSessionInViewFilter裡的幾個方法:

  Java代碼   protected void doFilterInternal(HttpServletRequest request,HttpServletResponse response,FilterChain filterChain)    throws ServletException, IOException {        SessionFactory sessionFactory = lookupSessionFactory();     logger.debug("Opening Hibernate Session in OpenSessionInViewFilter");     Session session = getSession(sessionFactory);     TransactionSynchronizationManager.bindResource(     sessionFactory, new SessionHolder(session));         try {           filterChain.doFilter(request, response);         }      finally {          TransactionSynchronizationManager.unbindResource(sessionFactory);       logger.debug("Closing Hibernate Session in OpenSessionInViewFilter");       closeSession(session, sessionFactory);        }       }    

 

  Java代碼   protected Session getSession(SessionFactory sessionFactory)       throws DataAccessResourceFailureException {       Session session = SessionFactoryUtils.getSession(sessionFactory, true);         session.setFlushMode(FlushMode.NEVER);         return session;       }     

 

  Java代碼  

聯繫我們

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