Write operations are not allowed in read-only mode

使用Spring提供的Open Session In View而引發Write operations are not allowed in read-only mode (FlushMode.NEVER) 錯誤解決:web

       在沒有使用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問題.spring

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

      OpenSessionInViewInterceptor配置app

  1. <beans>ide

  2. <bean name="openSessionInViewInterceptor" post

  3.    class="org.springframework.orm.hibernate3.support.OpenSessionInViewInterceptor"> 測試

  4.    <property name="sessionFactory"> 網站

  5.      <ref bean="sessionFactory"/> url

  6.    </property> 

  7. </bean>

  8. <bean id="urlMapping"

  9.    class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">

  10.    <property name="interceptors"> 

  11.      <list>

  12.        <ref bean="openSessionInViewInterceptor"/> 

  13.      </list> 

  14.    </property>

  15.    <property name="mappings">

  16.      ...

  17.    </property> 

  18. </bean>

  19.  ...

  20. </beans>

      OpenSessionInViewFilter配置

  1. <web-app> 

  2.   ... 

  3.   <filter> 

  4.      <filter-name>hibernateFilter</filter-name>

  5.      <filter-class>

  6.        org.springframework.orm.hibernate3.support.OpenSessionInViewFilter

  7.      </filter-class>

  8.      <!-- singleSession默認爲true,若設爲false則等於沒用OpenSessionInView -->

  9.      <init-param>

  10.        <param-name>singleSession</param-name>

  11.        <param-value>true</param-value> 

  12.      </init-param> 

  13.    </filter> 

  14.    ...

  15.    <filter-mapping>

  16.      <filter-name>hibernateFilter</filter-name> 

  17.      <url-pattern>*.do</url-pattern>

  18.    </filter-mapping>

  19.    ... 

  20.  </web-app>

      不少人在使用OpenSessionInView過程當中說起一個錯誤:

  1. org.springframework.dao.InvalidDataAccessApiUsageException: Write operations 

  2. are not allowed in read-only mode (FlushMode.NEVER) - turn your Session into 

  3. FlushMode.AUTO or remove 'readOnly' marker from transaction definition 

      看看OpenSessionInViewFilter裏的幾個方法

  1. 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);

     }

    }

  2.  protected Session getSession(SessionFactory sessionFactory)

       throws DataAccessResourceFailureException {

      Session session = SessionFactoryUtils.getSession(sessionFactory, true);

      session.setFlushMode(FlushMode.NEVER);

      return session;

  3.  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,使方法擁有寫權限。

  1.  public static void closeSessionIfNecessary(Session session, SessionFactory sessionFactory) 

  2.  throws CleanupFailureDataAccessException { 

  3.  if (session == null ||

        TransactionSynchronizationManager.hasResource(sessionFactory)) {

  4.     return; 

  5.   } 

  6.   logger.debug("Closing Hibernate session");

  7.   try { 

  8.     session.close(); 

  9.   } 

  10.   catch (JDBCException ex) {

  11.   // SQLException underneath 

  12.   throw new CleanupFailureDataAccessException("Could not close Hibernate session", ex.getSQLException()); 

  13.   } 

  14.   catch (HibernateException ex) {

  15.   throw new CleanupFailureDataAccessException("Could not close Hibernate session",  ex); 

  16.   }

  17. }  

也便是,若是有不是readOnly的transaction就能夠由Flush.NEVER轉爲Flush.AUTO,擁有 insert,update,delete操做權限,若是沒有transaction,而且沒有另外人爲地設flush model的話,則doFilter的整個過程都是Flush.NEVER。因此受transaction保護的方法有寫權限,沒受保護的則沒有。

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

  1.  <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> 

  2. <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,如

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

相關文章
相關標籤/搜索