OpenSessionInViewFilter作用及配置

一、作用

Spring爲我們解決Hibernate的Session的關閉與開啓問題。
Hibernate 允許對關聯對象、屬性進行延遲加載,但是必須保證延遲加載的操作限於同一個 Hibernate Session 範圍之內進行。如果 Service 層返回一個啓用了延遲加載功能的領域對象給 Web 層,當 Web 層訪問到那些需要延遲加載的數據時,由於加載領域對象的 Hibernate Session 已經關閉,這些導致延遲加載數據的訪問異常

(eg: org.hibernate.LazyInitializationException:(LazyInitializationException.java:42)
- failed to lazily initialize a collection of role: cn.easyjava.bean.product.ProductType.childtypes, no session or session was closed
org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: cn.easyjava.bean.product.ProductType.childtypes, no session or session was closed)

用來把一個Hibernate Session和一次完整的請求過程對應的線程相綁定。目的是爲了實現"Open Session in View"的模式。例如: 它允許在事務提交之後延遲加載顯示所需要的對象。

而Spring爲我們提供的OpenSessionInViewFilter過濾器爲我們很好的解決了這個問題。OpenSessionInViewFilter 的主要功能是用來把一個Hibernate Session和一次完整的請求過程對應的線程相綁定。目的是爲了實現"Open Session in View"的模式。例如: 它允許在事務提交之後延遲加載顯示所需要的對象。
OpenSessionInViewFilter 過濾器將 Hibernate Session 綁定到請求線程中,它將自動被 Spring 的事務管理器探測到。所以 OpenSessionInViewFilter 適用於 Service 層使用HibernateTransactionManager 或 JtaTransactionManager 進行事務管理的環境,也可以用於非事務只讀的數據操作中。

 

二、配置

它有兩種配置方式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。

OpenSessionInViewInterceptor配置

<beans>
 
<bean name="openSessionInViewInterceptor" 
 
class="org.springframework.orm.hibernate3.support.OpenSessionInViewInterceptor"> 
 
<property name="sessionFactory"> 
 
<ref bean="sessionFactory"/> 
 
</property> 
 
</bean>
 
<bean id="urlMapping"
 
class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
 
<property name="interceptors"> 
 
<list>
 
<ref bean="openSessionInViewInterceptor"/> 
 
</list> 
 
</property>
 
<property name="mappings">
 
...
 
</property> 
 
</bean>
 
...
 
</beans> OpenSessionInViewFilter配置 <web-app> 

  ...   <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>*.do</url-pattern>   </filter-mapping>   ...   </web-app> 

三、注意事項

很多人在使用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裏的幾個方法

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);
 
 }
 
}
 protected Session getSession(SessionFactory sessionFactory)

  throws DataAcce***esourceFailureException {   Session session = SessionFactoryUtils.getSession(sessionFactory, true);     session.setFlushMode(FlushMode.NEVER);     return session;   } 

protected void closeSession(Session session, SessionFactory sessionFactory)
 
throws CleanupFailureDataAccessException {
 
  SessionFactoryUtils.closeSessionIfNecessary(session, sessionFactory);
 
}
 可以看到OpenSessionInViewFilter在getSession的時候,會把獲取回來的session的flush mode 設爲FlushMode.NEVER。
然後把該sessionFactory綁定到 
TransactionSynchronizationManager,使request的整個過程都使用同一個session,在請求過後再接除該 
sessionFactory的綁定,最後closeSessionIfNecessary根據該 
session是否已和transaction綁定來決定是否關閉session。在這個過程中,若HibernateTemplate 
發現自當前session有不是readOnly的transaction,就會獲取到FlushMode.AUTO 
Session,使方法擁有寫權限。
public static void closeSessionIfNecessary(Session session, SessionFactory  sessionFactory) 

  throws CleanupFailureDataAccessException {   if (session == null ||   TransactionSynchronizationManager.hasResource(sessionFactory)) {   return;   }   logger.debug("Closing Hibernate session");   try {   session.close();   }   catch (JDBCException ex) {   // SQLException underneath   throw new CleanupFailureDataAccessException("Could not close Hibernate session", ex.getSQLException());   }   catch (HibernateException ex) {   throw new CleanupFailureDataAccessException("Could not close Hibernate session", ex);   }   } 

也即是,如果有不是readOnly的transaction就可以由Flush.NEVER轉爲Flush.AUTO,擁有 insert,update,delete操作權限,如果沒有transaction,並且沒有另外人爲地設flush model的話,則doFilter的整個過程都是Flush.NEVER。所以受transaction保護的方法有寫權限,沒受保護的則沒有。

採用spring的事務聲明,使方法受transaction控制

<bean id="baseTransaction"
 
class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean"
 
abstract="true">
 
<property name="transactionManager" ref="transactionManager"/>
 
<property name="proxyTargetClass" value="true"/>
 
<property name="transactionAttributes">
 
<props>
 
<prop key="get*">PROPAGATION_REQUIRED,readOnly</prop>
 
<prop key="find*">PROPAGATION_REQUIRED,readOnly</prop>
 
<prop key="load*">PROPAGATION_REQUIRED,readOnly</prop>
 
<prop key="save*">PROPAGATION_REQUIRED</prop>
 
<prop key="add*">PROPAGATION_REQUIRED</prop>
 
<prop key="update*">PROPAGATION_REQUIRED</prop>
 
<prop key="remove*">PROPAGATION_REQUIRED</prop>
 
</props>
 

對於上例,則以save,add,update,remove開頭的方法擁有可寫的事務,如果當前有某個方法,如命名爲 importExcel(),則因沒有transaction而沒有寫權限,這時若方法內有insert,update,delete操作的話,則需要手 動設置flush model爲Flush.AUTO,如

  1. session.setFlushMode(FlushMode.AUTO);

  2. session.save(user);

  3. session.flush();

 

盡 管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是個雙刃劍,放在公網上內容多流量大的網站請慎用

 

參考以及大段的copy自:

http://blog.csdn.net/sunsea08/archive/2009/09/12/4545186.aspx

http://blog.sina.com.cn/s/blog_5dc12c490100crr5.html


 
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章