天天看點

Spring的事務不復原處理

Spring的事務復原,當且僅當捕獲到RuntimeException類型異常時,才會復原,對普通Exception異常無效。

以下是我Service層捕獲異常,并抛出RuntimeException異常到Action層:

[java]  view plain copy

  1.        @Override  
  2. public void lock(String id) throws RuntimeException {  
  3.     try {  
  4.         this.loginUserDao.lock(id);  
  5.         LoginUser user = this.loginUserDao.findById(id);  
  6.         user.setSex("捕捉到異常後,抛出RuntimeException類型的異常");  
  7.         this.loginUserDao.save(user);  
  8.     } catch (Exception e) {  
  9.         // 捕捉到異常後,抛出RuntimeException類型的異常。  
  10.         // spring 事務隻在捕足到RuntimeException異常時,才會復原,對Exception無效  
  11.         throw new RuntimeException(e.getMessage());  
  12.     }  
  13. }  

spring中事務管理配置:

[html]  view plain copy

  1. <!-- 為sessionFactory定義事務管理器 -->  
  2. <bean id="transactionManager"  
  3.     class="org.springframework.orm.hibernate3.HibernateTransactionManager">  
  4.     <property name="sessionFactory">  
  5.         <ref local="sessionFactory" />  
  6.     </property>  
  7. </bean>  
  8. <!-- 定義事務攔截器 -->  
  9. <bean id="transactionInterceptor"  
  10.     class="org.springframework.transaction.interceptor.TransactionInterceptor">  
  11.     <!-- 為事務攔截器注入一個事務管理器 -->  
  12.     <property name="transactionManager" ref="transactionManager" />  
  13.     <property name="transactionAttributes">  
  14.         <!-- 定義事務傳播屬性 PROPAGATION_REQUIRED:表示如果事務不存在,則建立一個新事務,如果存在,則加入到該事務。 -->  
  15.         <props>  
  16.             <prop key="save*">PROPAGATION_REQUIRED</prop>  
  17.             <prop key="add*">PROPAGATION_REQUIRED</prop>  
  18.             <prop key="delete*">PROPAGATION_REQUIRED</prop>  
  19.             <prop key="update*">PROPAGATION_REQUIRED</prop>  
  20.             <prop key="lock*">PROPAGATION_REQUIRED</prop>  
  21.             <prop key="unLock*">PROPAGATION_REQUIRED</prop>  
  22.             <prop key="find*">PROPAGATION_REQUIRED,readOnly</prop>  
  23.             <prop key="list*">PROPAGATION_REQUIRED,readOnly</prop>  
  24.             <prop key="get*">PROPAGATION_REQUIRED,readOnly</prop>  
  25.             <prop key="*">PROPAGATION_REQUIRED,readOnly</prop>  
  26.         </props>  
  27.     </property>  
  28. </bean>  
  29. <!-- 定義攔截器要攔截的bean -->  
  30. <bean id="autoProxy"  
  31.     class="org.springframework.aop.framework.autoproxy.BeanNameAutoProxyCreator">  
  32.     <property name="beanNames">  
  33.         <list>  
  34.             <!-- 攔截所有名字以Service結尾的bean進行代理 -->  
  35.             <value>*Service</value>  
  36.         </list>  
  37.     </property>  
  38.     <property name="interceptorNames">  
  39.         <list>  
  40.             <value>transactionInterceptor</value>  
  41.         </list>  
  42.     </property>  
  43. </bean>