OpenSessionInViewFilter原理以及爲什麼要用OpenSessionInViewFilter

1、說說爲什麼使用lazy

當使用Hibernate中的one-to-many、many-to one、many-to-many關係映射的時候,一個對象中會包含一個或多個Set來關聯其他的對象。例如:user-groups,當程序取user 對象時,如果一個用戶有多個自定義組,那麼程序將把組的信息也讀取出來,在log中可以看到兩個sql的輸出。但是在頁面的顯示上,也許並不需要顯示這個用戶相關組的信息,這樣系統的消耗就白白浪費了,於是hibernate提供了lazy(延遲加載)的方法來避免這一情況的發生,我們只需要在 user.hbm.xml中設置lazy=true,就能實現延遲加載。

代碼

 

<set name="groupses" table="usergroups" catalog="many" cascade="save-update" lazy="true">  
            <key>   
                <column name="userid" length="32" not-null="true" />   
            </key>   
            <many-to-many entity-name="com.example.model.Groups">   
                <column name="groupid" length="32" not-null="true" />   
            </many-to-many>   
        </set>  


2、說說爲什麼使用OpenSessionInView

當hibernate+spring配合使用的時候,如果設置了lazy=true,那麼在讀取數據的時候,當讀取了父數據後,hibernate會自動關閉session,這樣,當要使用子數據的時候,系統會拋出lazyinit的錯誤,這時就需要使用spring提供的 OpenSessionInViewFilter,

OpenSessionInViewFilter主要是保持Session狀態知道request將全部頁面發送到客戶端,這樣就可以解決延遲加載帶來的問題

3、說說Webwork中使用OpenSessionInView的注意事項

web.xml中的配置要注意先後順序,OpenSessionInViewFilter要在struts2的filter前面,(這個是爲什麼呢?)否則系統會報錯。

代碼

 

<filter>   
        <filter-name>opensession</filter-name>   
        <filter-class>   
              org.springframework.orm.hibernate3.support.OpenSessionInViewFilter   
        </filter-class>   
        <init-param>   
            <param-name>singleSession</param-name>   
            <param-value>true</param-value>   
        </init-param>   
        <init-param>   
            <param-name>sessionFactoryBeanName</param-name>   
            <param-value>mySessionFactory</param-value>     
        </init-param>   
    </filter>   
         
    <filter>   
        <filter-name>webwork</filter-name>   
        <filter-class>com.opensymphony.webwork.dispatcher.FilterDispatcher</filter-class>  
    </filter>   
         <filter-mapping>   
      <filter-name>opensession</filter-name>   
      <url-pattern>/*</url-pattern>     
    </filter-mapping>   
    <filter-mapping>   
        <filter-name>webwork</filter-name>   
        <url-pattern>/*</url-pattern>   
    </filter-mapping>  


對於OpenSessionInView的配置中,singleSession應該設置爲true(在哪兒設置呢?),表示一個request只能打開一個 session,如果設置爲false的話,session可以被打開多個,這時在update、delete的時候會出現打開多個session的異常。

用了OpenSessionInView的缺點:

但是當設置爲true的時候,系統的性能會因爲用戶的網絡狀況受到影響,當request在生成頁面完成後,session纔會被釋放,所以如果用戶的網絡狀況比較差,那麼連接池中的鏈接會遲遲不被回收,造成內存增加,系統性能受損。但是如果不用這種方法的話,lazy模式有體現不出它的優點,用?不用?兩難啊



//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

在沒有使用Spring提供的Open Session In View情況下,因需要在service(or Dao)層裏把session關閉,所以lazy loading 爲true的話,要在應用層內把關係集合都初始化,如 company.getEmployees(),否則Hibernate拋session already closed Exception;    Open Session In View提供了一種簡便的方法,較好地解決了lazy loading問題.

    它有兩種配置方式OpenSessionInViewInterceptor和OpenSessionInViewFilter(具體參看SpringSide),功能相同,只是一個在web.xml配置,另一個在application.xml配置而已。

    OpenSessionInView在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 DataAccessResourceFailureException {

 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>

        </property>

    </bean>


    <bean id="userService" parent="baseTransaction"> 
        <property name="target">

            <bean class="com.phopesoft.security.service.impl.UserServiceImpl"/>

        </property>

    </bean>

 

 

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

 

session.setFlushMode(FlushMode.AUTO);

 

session.save(user);

 

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



////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

由於OpenSessionInViewFilter把session綁在當前線程上,導致session的生命週期比事務要長,這期間所有事務性操作都在複用這同一個session,由此產生了一些“怪問題”:

1.出現如下錯誤:

     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 在把session綁在當前線程上的時候,會把session的flush mode 設爲FlushMode.NEVER,因此,如果某個方法沒有事務或者有隻讀事務,則不能對session做insert,update,delete操作,除非事先把session的flush mode手動設爲auto

方案:

1、將singleSession設爲false,這樣只要改 web.xml,缺點是Hibernate Session的Instance可能會大增,使用的JDBC Connection量也會大增,如果Connection Pool的maxPoolSize設得太小,很容易就出問題。<!-- singleSession默認爲true,若設爲false則等於沒用OpenSessionInView -->

2、在控制器中自行管理Session的FlushMode,麻煩的是每個有Modify的Method都要多幾行程式

session.setFlushMode(FlushMode.AUTO);

session.update(user);

session.flush();

3、Extend OpenSessionInViewFilter,Override protected Session getSession(SessionFactory sessionFactory),將FlushMode直接改爲Auto。

4、讓方法受Spring的事務控制(service和配置文件對應)

發佈了17 篇原創文章 · 獲贊 18 · 訪問量 15萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章