沉睡森林@漂在北京

          本處文章除注明“轉(zhuǎn)載”外均為原創(chuàng),轉(zhuǎn)載請(qǐng)注明出處。

            BlogJava :: 首頁 :: 新隨筆 :: 聯(lián)系 :: 聚合  :: 管理 ::
            152 隨筆 :: 4 文章 :: 114 評(píng)論 :: 0 Trackbacks

          看到了關(guān)于Spring提供的Open Session In View的一篇文章,很詳細(xì)的介紹了相關(guān)細(xì)節(jié)。下面的文章轉(zhuǎn)載自:
          http://blog.sina.com.cn/s/blog_5dc12c490100crr5.html


          使用Spring提供的Open Session In View而引起Write operations are not allowed in read-only mode (FlushMode.NEVER) 錯(cuò)誤解決:
              在沒有使用Spring提供的Open Session In View情況下,因需要在service(or Dao)層里把session關(guān)閉,所以lazy loading 為true的話,要在應(yīng)用層內(nèi)把關(guān)系集合都初始化,如 company.getEmployees(),否則Hibernate拋session already closed Exception;    Open Session In View提供了一種簡便的方法,較好地解決了lazy loading問題.
              它有兩種配置方式OpenSessionInViewInterceptor和OpenSessionInViewFilter(具體參看SpringSide),功能相同,只是一個(gè)在web.xml配置,另一個(gè)在application.xml配置而已。
              Open Session In View在request把session綁定到當(dāng)前thread期間一直保持hibernate session在open狀態(tài),使session在request的整個(gè)期間都可以使用,如在View層里PO也可以lazy loading數(shù)據(jù),如 ${ company.employees }。當(dāng)View 層邏輯完成后,才會(huì)通過Filter的doFilter方法或Interceptor的postHandle方法自動(dòng)關(guān)閉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默認(rèn)為true,若設(shè)為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過程中提及一個(gè)錯(cuò)誤:
          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里的幾個(gè)方法
           
          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的時(shí)候,會(huì)把獲取回來的session的flush mode 設(shè)為FlushMode.NEVER。然后把該sessionFactory綁定到 TransactionSynchronizationManager,使request的整個(gè)過程都使用同一個(gè)session,在請(qǐng)求過后再接除該 sessionFactory的綁定,最后closeSessionIfNecessary根據(jù)該 session是否已和transaction綁定來決定是否關(guān)閉session。在這個(gè)過程中,若HibernateTemplate 發(fā)現(xiàn)自當(dāng)前session有不是readOnly的transaction,就會(huì)獲取到FlushMode.AUTO Session,使方法擁有寫權(quán)限。
           
          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轉(zhuǎn)為Flush.AUTO,擁有 insert,update,delete操作權(quán)限,如果沒有transaction,并且沒有另外人為地設(shè)flush model的話,則doFilter的整個(gè)過程都是Flush.NEVER。所以受transaction保護(hù)的方法有寫權(quán)限,沒受保護(hù)的則沒有。
          采用spring的事務(wù)聲明,使方法受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>
           
          對(duì) 于上例,則以save,add,update,remove開頭的方法擁有可寫的事務(wù),如果當(dāng)前有某個(gè)方法,如命名為importExcel(),則因沒 有transaction而沒有寫權(quán)限,這時(shí)若方法內(nèi)有insert,update,delete操作的話,則需要手動(dòng)設(shè)置flush model為Flush.AUTO,如
          session.setFlushMode(FlushMode.AUTO);
          session.save(user);
          session.flush();
                盡 管Open Session In View看起來還不錯(cuò),其實(shí)副作用不少。看回上面OpenSessionInViewFilter的doFilterInternal方法代碼,這個(gè)方法 實(shí)際上是被父類的doFilter調(diào)用的,因此,我們可以大約了解的OpenSessionInViewFilter調(diào)用流程: request(請(qǐng)求)->open session并開始transaction->controller->View(Jsp)->結(jié)束transaction并 close session.
               一切看起來很正確,尤其是在本地開發(fā)測(cè)試的時(shí)候沒出現(xiàn)問題,但試想下如果流程中的某一步被阻塞的話,那在這期間connection就一直被占用而不釋 放。最有可能被阻塞的就是在寫Jsp這步,一方面可能是頁面內(nèi)容大,response.write的時(shí)間長,另一方面可能是網(wǎng)速慢,服務(wù)器與用戶間傳輸時(shí) 間久。當(dāng)大量這樣的情況出現(xiàn)時(shí),就有連接池連接不足,造成頁面假死現(xiàn)象。
          Open Session In View是個(gè)雙刃劍,放在公網(wǎng)上內(nèi)容多流量大的網(wǎng)站請(qǐng)慎用。

          posted on 2009-05-21 20:45 王總兵 閱讀(1895) 評(píng)論(2)  編輯  收藏 所屬分類: Spring

          評(píng)論

          # re: [轉(zhuǎn)]Hibernate和spring結(jié)合的OpenSessionInViewFilter 2009-10-26 21:32 pei
          調(diào)用流程: request(請(qǐng)求)->open session并開始transaction->controller->View(Jsp)->結(jié)束transaction并 close session.

          好像說的不對(duì)。
          我在spring專業(yè)編程這本書上看到,是說事務(wù)在服務(wù)層中結(jié)束  回復(fù)  更多評(píng)論
            

          # re: [轉(zhuǎn)]Hibernate和spring結(jié)合的OpenSessionInViewFilter 2009-10-27 09:08 wangchangbing
          @pei

          你沒有好好的看這個(gè)文章,對(duì)OpenSessionInViewFilter的認(rèn)識(shí)還不是很到位
          事物在服務(wù)層結(jié)束是正常的做法,但是我們使用了延遲加載技術(shù)
          事物在展示層做完后在關(guān)閉  回復(fù)  更多評(píng)論
            

          主站蜘蛛池模板: 长宁区| 通河县| 郓城县| 金秀| 台北市| 高碑店市| 陆丰市| 射洪县| 顺平县| 泾阳县| 山阴县| 大连市| 如东县| 湘潭县| 德保县| 乐山市| 梅州市| 濮阳市| 屏南县| 蛟河市| 金昌市| 清新县| 建阳市| 高台县| 孝感市| 林口县| 略阳县| 淮滨县| 岢岚县| 老河口市| 襄汾县| 宁陵县| 定安县| 苗栗县| 平湖市| 巧家县| 玉树县| 罗城| 达日县| 苗栗市| 大埔区|