posts - 0, comments - 77, trackbacks - 0, articles - 356
            BlogJava :: 首頁 :: 新隨筆 :: 聯系 :: 聚合  :: 管理

          Open Session In View

          Posted on 2007-09-09 18:15 semovy 閱讀(785) 評論(0)  編輯  收藏 所屬分類: Hibernatespring
          在沒有使用Spring提供的Open Session In View情況下,因需要在service(or Dao)層里把session關閉,所以lazy loading true的話,要在應用層內把關系集合都初始化,如 company.getEmployees(),否則Hibernatesession already closed Exception;    Open Session In View提供了一種簡便的方法,較好地解決了lazy loading問題.

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

              Open Session In Viewrequestsession綁定到當前thread期間一直保持hibernate sessionopen狀態,使sessionrequest的整個期間都可以使用,如在View層里PO也可以lazy loading數據,如 ${ company.employees }。當View 層邏輯完成后,才會通過FilterdoFilter方法或InterceptorpostHandle方法自動關閉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里的opensession方法

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

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

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

           

          hibernate open session in view 拋出異常解決方法

           在使用open-session-in-view的時候,如果使用不當,有可能拋出兩種異常
          1,NonUniqueObjectException
          2,在配合spring使用的時候會可能會拋出org.springframework.dao.InvalidDataAccessApiUsageException

          先說1,這個異常的拋出原因和解決辦法見這里:
          javaeye上有了很好的事例:http://www.javaeye.com/topic/11581
          解決辦法可以用merge,也可以別的辦法。
          出現的原因,可以參考一下我前邊的文章中將merge和update的區別的內容。
          http://www.aygfsteel.com/dreamstone/archive/2007/07/29/133071.html

          2的解決辦法:在這里
          springside的一篇文章做了詳細說明
          http://calvin.blog.javascud.org/post/46.htm

          好了,現在問題解決了,但關于open-session-in-view的使用還有一些探討,是否應該使用,使用的好處與壞處。
          見這兩篇jdon上的文章:
          http://www.jdon.com/jivejdon/thread/22374.html
          http://www.jdon.com/jivejdon/thread/28955.html

          主站蜘蛛池模板: 广南县| 小金县| 周口市| 体育| 社旗县| 原平市| 伊金霍洛旗| 乌恰县| 民乐县| 新源县| 伊宁县| 清水县| 道孚县| 天长市| 宝应县| 六安市| 任丘市| 永登县| 蕲春县| 巨鹿县| 射洪县| 杨浦区| 青河县| 泰宁县| 兴文县| 连江县| 临桂县| 石景山区| 建德市| 习水县| 那曲县| 迁安市| 沅江市| 平塘县| 柳江县| 巴马| 汉源县| 惠东县| 彭泽县| 无极县| 鸡泽县|