spring 事务管理

前段时间对Spring的事务配置做了比较深入的研究,在此之间对Spring的事务配置虽说也配置过,但是一直没有一个清楚的认识。通过这次的学习发觉Spring的事务配置只要把思路理清,还是比较好掌握的。

    总结如下:

    Spring配置文件中关于事务配置总是由三个组成部分,分别是DataSource、TransactionManager和代理机制这三部分,无论哪种配置方式,一般变化的只是代理机制这部分。

    DataSource、TransactionManager这两部分只是会根据数据访问方式有所变化,比如使用Hibernate进行数据访问时,DataSource实际为SessionFactory,TransactionManager的实现为HibernateTransactionManager。

    具体如下图:

根据代理机制的不同,总结了五种Spring事务的配置方式,配置文件如下:

    第一种方式:每个Bean都有一个代理

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <beans xmlns="http://www.springframework.org/schema/beans"
 3     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 4     xmlns:context="http://www.springframework.org/schema/context"
 5     xmlns:aop="http://www.springframework.org/schema/aop"
 6     xsi:schemaLocation="http://www.springframework.org/schema/beans 
 7            http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
 8            http://www.springframework.org/schema/context
 9            http://www.springframework.org/schema/context/spring-context-2.5.xsd
10            http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd">
11 
12     <bean id="sessionFactory"  
13             class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">  
14         <property name="configLocation" value="classpath:hibernate.cfg.xml" />  
15         <property name="configurationClass" value="org.hibernate.cfg.AnnotationConfiguration" />
16     </bean>  
17 
18     <!-- 定义事务管理器(声明式的事务) -->  
19     <bean id="transactionManager"
20         class="org.springframework.orm.hibernate3.HibernateTransactionManager">
21         <property name="sessionFactory" ref="sessionFactory" />
22     </bean>
23     
24     <!-- 配置DAO -->
25     <bean id="userDaoTarget" class="com.bluesky.spring.dao.UserDaoImpl">
26         <property name="sessionFactory" ref="sessionFactory" />
27     </bean>
28     
29     <bean id="userDao"  
30         class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean">  
31            <!-- 配置事务管理器 -->  
32            <property name="transactionManager" ref="transactionManager" />     
33         <property name="target" ref="userDaoTarget" />  
34          <property name="proxyInterfaces" value="com.bluesky.spring.dao.GeneratorDao" />
35         <!-- 配置事务属性 -->  
36         <property name="transactionAttributes">  
37             <props>  
38                 <prop key="*">PROPAGATION_REQUIRED</prop>
39             </props>  
40         </property>  
41     </bean>  
42 </beans>

第二种方式:所有Bean共享一个代理基类

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <beans xmlns="http://www.springframework.org/schema/beans"
 3     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 4     xmlns:context="http://www.springframework.org/schema/context"
 5     xmlns:aop="http://www.springframework.org/schema/aop"
 6     xsi:schemaLocation="http://www.springframework.org/schema/beans 
 7            http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
 8            http://www.springframework.org/schema/context
 9            http://www.springframework.org/schema/context/spring-context-2.5.xsd
10            http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd">
11 
12     <bean id="sessionFactory"  
13             class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">  
14         <property name="configLocation" value="classpath:hibernate.cfg.xml" />  
15         <property name="configurationClass" value="org.hibernate.cfg.AnnotationConfiguration" />
16     </bean>  
17 
18     <!-- 定义事务管理器(声明式的事务) -->  
19     <bean id="transactionManager"
20         class="org.springframework.orm.hibernate3.HibernateTransactionManager">
21         <property name="sessionFactory" ref="sessionFactory" />
22     </bean>
23     
24     <bean id="transactionBase"  
25             class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean"  
26             lazy-init="true" abstract="true">  
27         <!-- 配置事务管理器 -->  
28         <property name="transactionManager" ref="transactionManager" />  
29         <!-- 配置事务属性 -->  
30         <property name="transactionAttributes">  
31             <props>  
32                 <prop key="*">PROPAGATION_REQUIRED</prop>  
33             </props>  
34         </property>  
35     </bean>    
36    
37     <!-- 配置DAO -->
38     <bean id="userDaoTarget" class="com.bluesky.spring.dao.UserDaoImpl">
39         <property name="sessionFactory" ref="sessionFactory" />
40     </bean>
41     
42     <bean id="userDao" parent="transactionBase" >  
43         <property name="target" ref="userDaoTarget" />   
44     </bean>
45 </beans>

第三种方式:使用拦截器

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xsi:schemaLocation="http://www.springframework.org/schema/beans 
           http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
           http://www.springframework.org/schema/context
           http://www.springframework.org/schema/context/spring-context-2.5.xsd
           http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd">

    <bean id="sessionFactory"  
            class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">  
        <property name="configLocation" value="classpath:hibernate.cfg.xml" />  
        <property name="configurationClass" value="org.hibernate.cfg.AnnotationConfiguration" />
    </bean>  

    <!-- 定义事务管理器(声明式的事务) -->  
    <bean id="transactionManager"
        class="org.springframework.orm.hibernate3.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory" />
    </bean> 
   
    <bean id="transactionInterceptor"  
        class="org.springframework.transaction.interceptor.TransactionInterceptor">  
        <property name="transactionManager" ref="transactionManager" />  
        <!-- 配置事务属性 -->  
        <property name="transactionAttributes">  
            <props>  
                <prop key="*">PROPAGATION_REQUIRED</prop>  
            </props>  
        </property>  
    </bean>
      
    <bean class="org.springframework.aop.framework.autoproxy.BeanNameAutoProxyCreator">  
        <property name="beanNames">  
            <list>  
                <value>*Dao</value>
            </list>  
        </property>  
        <property name="interceptorNames">  
            <list>  
                <value>transactionInterceptor</value>  
            </list>  
        </property>  
    </bean>  
  
    <!-- 配置DAO -->
    <bean id="userDao" class="com.bluesky.spring.dao.UserDaoImpl">
        <property name="sessionFactory" ref="sessionFactory" />
    </bean>
</beans>

第四种方式:使用tx标签配置的拦截器

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <beans xmlns="http://www.springframework.org/schema/beans"
 3     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 4     xmlns:context="http://www.springframework.org/schema/context"
 5     xmlns:aop="http://www.springframework.org/schema/aop"
 6     xmlns:tx="http://www.springframework.org/schema/tx"
 7     xsi:schemaLocation="http://www.springframework.org/schema/beans 
 8            http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
 9            http://www.springframework.org/schema/context
10            http://www.springframework.org/schema/context/spring-context-2.5.xsd
11            http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
12            http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">
13 
14     <context:annotation-config />
15     <context:component-scan base-package="com.bluesky" />
16 
17     <bean id="sessionFactory"  
18             class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">  
19         <property name="configLocation" value="classpath:hibernate.cfg.xml" />  
20         <property name="configurationClass" value="org.hibernate.cfg.AnnotationConfiguration" />
21     </bean>  
22 
23     <!-- 定义事务管理器(声明式的事务) -->  
24     <bean id="transactionManager"
25         class="org.springframework.orm.hibernate3.HibernateTransactionManager">
26         <property name="sessionFactory" ref="sessionFactory" />
27     </bean>
28 
29     <tx:advice id="txAdvice" transaction-manager="transactionManager">
30         <tx:attributes>
31             <tx:method name="*" propagation="REQUIRED" />
32         </tx:attributes>
33     </tx:advice>
34     
35     <aop:config>
36         <aop:pointcut id="interceptorPointCuts"
37             expression="execution(* com.bluesky.spring.dao.*.*(..))" />
38         <aop:advisor advice-ref="txAdvice"
39             pointcut-ref="interceptorPointCuts" />        
40     </aop:config>      
41 </beans>

第五种方式:全注解

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <beans xmlns="http://www.springframework.org/schema/beans"
 3     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 4     xmlns:context="http://www.springframework.org/schema/context"
 5     xmlns:aop="http://www.springframework.org/schema/aop"
 6     xmlns:tx="http://www.springframework.org/schema/tx"
 7     xsi:schemaLocation="http://www.springframework.org/schema/beans 
 8            http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
 9            http://www.springframework.org/schema/context
10            http://www.springframework.org/schema/context/spring-context-2.5.xsd
11            http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
12            http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">
13 
14     <context:annotation-config />
15     <context:component-scan base-package="com.bluesky" />
16 
17     <tx:annotation-driven transaction-manager="transactionManager"/>
18 
19     <bean id="sessionFactory"  
20             class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">  
21         <property name="configLocation" value="classpath:hibernate.cfg.xml" />  
22         <property name="configurationClass" value="org.hibernate.cfg.AnnotationConfiguration" />
23     </bean>  
24 
25     <!-- 定义事务管理器(声明式的事务) -->  
26     <bean id="transactionManager"
27         class="org.springframework.orm.hibernate3.HibernateTransactionManager">
28         <property name="sessionFactory" ref="sessionFactory" />
29     </bean>
30     
31 </beans>

此时在DAO上需加上@Transactional注解,如下:

 1 package com.bluesky.spring.dao;
 2 
 3 import java.util.List;
 4 
 5 import org.hibernate.SessionFactory;
 6 import org.springframework.beans.factory.annotation.Autowired;
 7 import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
 8 import org.springframework.stereotype.Component;
 9 
10 import com.bluesky.spring.domain.User;
11 
12 @Transactional
13 @Component("userDao")
14 public class UserDaoImpl extends HibernateDaoSupport implements UserDao {
15 
16     public List<User> listUsers() {
17         return this.getSession().createQuery("from User").list();
18     }
19     
20      
21 }

Spring声明式事务让我们从复杂的事务处理中得到解脱。使得我们再也无需要去处理获得连接、关闭连接、事务提交和回滚等这些操作。再也无需要我们在与事务相关的方法中处理大量的try…catch…finally代码。 
我们在使用Spring声明式事务时,有一个非常重要的概念就是事务属性。事务属性通常由事务的传播行为,事务的隔离级别,事务的超时值和事务只读标志组成。我们在进行事务划分时,需要进行事务定义,也就是配置事务的属性。 
Spring在TransactionDefinition接口中定义这些属性,以供PlatfromTransactionManager使用, PlatfromTransactionManager是spring事务管理的核心接口。 

1 TransactionDefinition  
2 public interface TransactionDefinition {  
3  int getPropagationBehavior();  
4  int getIsolationLevel();  
5  int getTimeout();  
6  boolean isReadOnly();  
7 }  

getTimeout()方法,它返回事务必须在多少秒内完成。 
isReadOnly(),事务是否只读,事务管理器能够根据这个返回值进行优化,确保事务是只读的。 
getIsolationLevel()方法返回事务的隔离级别,事务管理器根据它来控制另外一个事务可以看到本事务内的哪些数据。 

Spring事务机制主要包括声明式事务和编程式事务,此处侧重讲解声明式事务,编程式事务在实际开发中得不到广泛使用,仅供学习参考。

Spring声明式事务让我们从复杂的事务处理中得到解脱。使得我们再也无需要去处理获得连接、关闭连接、事务提交和回滚等这些操作。再也无需要我们在与事务相关的方法中处理大量的try…catch…finally代码。我们在使用Spring声明式事务时,有一个非常重要的概念就是事务属性。事务属性通常由事务的传播行为,事务的隔离级别,事务的超时值和事务只读标志组成。我们在进行事务划分时,需要进行事务定义,也就是配置事务的属性。

下面分别详细讲解,事务的四种属性,仅供诸位学习参考:

Spring在TransactionDefinition接口中定义这些属性,以供PlatfromTransactionManager使用, PlatfromTransactionManager是spring事务管理的核心接口。

1 public interface TransactionDefinition { 
2     int getPropagationBehavior();//返回事务的传播行为。 
3     int getIsolationLevel();//返回事务的隔离级别,事务管理器根据它来控制另外一个事务可以看到本事务内的哪些数据。 
4     int getTimeout();//返回事务必须在多少秒内完成。 
5     boolean isReadOnly();//事务是否只读,事务管理器能够根据这个返回值进行优化,确保事务是只读的。 
6 }

1. TransactionDefinition接口中定义五个隔离级别:

ISOLATION_DEFAULT 这是一个PlatfromTransactionManager默认的隔离级别,使用数据库默认的事务隔离级别.另外四个与JDBC的隔离级别相对应;

ISOLATION_READ_UNCOMMITTED 这是事务最低的隔离级别,它充许别外一个事务可以看到这个事务未提交的数据。这种隔离级别会产生脏读,不可重复读和幻像读。

ISOLATION_READ_COMMITTED  保证一个事务修改的数据提交后才能被另外一个事务读取。另外一个事务不能读取该事务未提交的数据。这种事务隔离级别可以避免脏读出现,但是可能会出现不可重复读和幻像读。

ISOLATION_REPEATABLE_READ  这种事务隔离级别可以防止脏读,不可重复读。但是可能出现幻像读。它除了保证一个事务不能读取另一个事务未提交的数据外,还保证了避免下面的情况产生(不可重复读)。

ISOLATION_SERIALIZABLE 这是花费最高代价但是最可靠的事务隔离级别。事务被处理为顺序执行。除了防止脏读,不可重复读外,还避免了幻像读。

1: Dirty reads(脏读)。也就是说,比如事务A的未提交(还依然缓存)的数据被事务B读走,如果事务A失败回滚,会导致事务B所读取的的数据是错误的。 
2: non-repeatable reads(数据不可重复读)。比如事务A中两处读取数据-total-的值。在第一读的时候,total是100,然后事务B就把total的数据改成 200,事务A再读一次,结果就发现,total竟然就变成200了,造成事务A数据混乱。 
3: phantom reads(幻象读数据),这个和non-repeatable reads相似,也是同一个事务中多次读不一致的问题。但是non-repeatable reads的不一致是因为他所要取的数据集被改变了(比如total的数据),但是phantom reads所要读的数据的不一致却不是他所要读的数据集改变,而是他的条件数据集改变。比如Select account.id where account.name="ppgogo*",第一次读去了6个符合条件的id,第二次读取的时候,由于事务b把一个帐号的名字由"dd"改成"ppgogo1",结果取出来了7个数据。

2. 在TransactionDefinition接口中定义了七个事务传播行为:

(1)PROPAGATION_REQUIRED 如果存在一个事务,则支持当前事务。如果没有事务则开启一个新的事务。

Java代码:

 1 //事务属性 PROPAGATION_REQUIRED 
 2 methodA{ 
 3  …… 
 4  methodB(); 
 5  …… 
 6 }
 7 
 8 //事务属性 PROPAGATION_REQUIRED 
 9 methodB{ 
10    …… 
11 }

 

使用spring声明式事务,spring使用AOP来支持声明式事务,会根据事务属性,自动在方法调用之前决定是否开启一个事务,并在方法执行之后决定事务提交或回滚事务。

 

单独调用methodB方法:

Java代码

1 main{ 
2 
3  metodB(); 
4 
5 }   

 

相当于

Java代码

 1 Main{ 
 2 
 3  Connection con=null; 
 4 
 5  try{ 
 6 
 7   con = getConnection(); 
 8 
 9   con.setAutoCommit(false); 
10 
11   //方法调用
12 
13   methodB(); 
14 
15   //提交事务
16 
17   con.commit(); 
18 
19  } 
20 
21  Catch(RuntimeException ex){ 
22 
23   //回滚事务
24 
25   con.rollback();   
26 
27  } 
28  finally{ 
29 
30  //释放资源
31 
32  closeCon(); 
33 
34  } 
35 
36 } 

 


Spring保证在methodB方法中所有的调用都获得到一个相同的连接。在调用methodB时,没有一个存在的事务,所以获得一个新的连接,开启了一个新的事务。

单独调用MethodA时,在MethodA内又会调用MethodB.

执行效果相当于:

Java代码

          

 1 main{ 
 2  Connection con = null; 
 3  try{
 4   con = getConnection(); 
 5   methodA(); 
 6   con.commit(); 
 7  }
 8  catch(RuntimeException ex){ 
 9   con.rollback(); 
10  }
11  finally{ 
12   closeCon(); 
13  }
14 } 

 

调用MethodA时,环境中没有事务,所以开启一个新的事务.当在MethodA中调用MethodB时,环境中已经有了一个事务,所以methodB就加入当前事务。

(2)PROPAGATION_SUPPORTS 如果存在一个事务,支持当前事务。如果没有事务,则非事务的执行。但是对于事务同步的事务管理器,PROPAGATION_SUPPORTS与不使用事务有少许不同。

Java代码: 

1 //事务属性 PROPAGATION_REQUIRED 
2 methodA(){ 
3   methodB(); 
4 }
5 
6 //事务属性 PROPAGATION_SUPPORTS 
7 methodB(){ 
8   …… 
9 }

 

单纯的调用methodB时,methodB方法是非事务的执行的。当调用methdA时,methodB则加入了methodA的事务中,事务地执行。

(3)PROPAGATION_MANDATORY 如果已经存在一个事务,支持当前事务。如果没有一个活动的事务,则抛出异常。

Java代码:

1 //事务属性 PROPAGATION_REQUIRED 
2 methodA(){ 
3   methodB(); 
4 }
5 
6 //事务属性 PROPAGATION_MANDATORY 
7 methodB(){ 
8     …… 
9 }

 

当单独调用methodB时,因为当前没有一个活动的事务,则会抛出异常throw new IllegalTransactionStateException("Transaction propagation 'mandatory' but no existing transaction found");当调用methodA时,methodB则加入到methodA的事务中,事务地执行。


(4)PROPAGATION_REQUIRES_NEW 总是开启一个新的事务。如果一个事务已经存在,则将这个存在的事务挂起。

Java代码:

 1 //事务属性 PROPAGATION_REQUIRED 
 2 methodA(){ 
 3  doSomeThingA(); 
 4  methodB(); 
 5  doSomeThingB(); 
 6 }
 7 
 8 //事务属性 PROPAGATION_REQUIRES_NEW 
 9 methodB(){ 
10  …… 
11 }

 

Java代码:

1 main(){ 
2   methodA(); 
3 }

 

相当于

Java代码:

 1 main(){ 
 2   TransactionManager tm = null; 
 3     try{ 
 4       //获得一个JTA事务管理器 
 5     tm = getTransactionManager(); 
 6     tm.begin();//开启一个新的事务 
 7     Transaction ts1 = tm.getTransaction(); 
 8     doSomeThing(); 
 9     tm.suspend();//挂起当前事务 
10     try{ 
11       tm.begin();//重新开启第二个事务 
12       Transaction ts2 = tm.getTransaction(); 
13       methodB(); 
14       ts2.commit();//提交第二个事务 
15        } 
16          Catch(RunTimeException ex){ 
17       ts2.rollback();//回滚第二个事务 
18       }
19       finally{ 
20          //释放资源 
21        }
22     //methodB执行完后,复恢第一个事务 
23     tm.resume(ts1); 
24         doSomeThingB(); 
25     ts1.commit();//提交第一个事务 
26     }
27     catch(RunTimeException ex){ 
28       ts1.rollback();//回滚第一个事务 
29     }
30     finally{ 
31       //释放资源 
32     }
33 }

 

在这里,我把ts1称为外层事务,ts2称为内层事务。从上面的代码可以看出,ts2与ts1是两个独立的事务,互不相干。Ts2是否成功并不依赖于 ts1。如果methodA方法在调用methodB方法后的doSomeThingB方法失败了,而methodB方法所做的结果依然被提交。而除了 methodB之外的其它代码导致的结果却被回滚了。使用PROPAGATION_REQUIRES_NEW,需要使用 JtaTransactionManager作为事务管理器。 
(5)PROPAGATION_NOT_SUPPORTED  总是非事务地执行,并挂起任何存在的事务。使用PROPAGATION_NOT_SUPPORTED,也需要使用JtaTransactionManager作为事务管理器。(代码示例同上,可同理推出)

(6)PROPAGATION_NEVER 总是非事务地执行,如果存在一个活动事务,则抛出异常;

(7)PROPAGATION_NESTED如果一个活动的事务存在,则运行在一个嵌套的事务中. 如果没有活动事务, 则按TransactionDefinition.PROPAGATION_REQUIRED 属性执行。这是一个嵌套事务,使用JDBC 3.0驱动时,仅仅支持DataSourceTransactionManager作为事务管理器。需要JDBC 驱动的java.sql.Savepoint类。有一些JTA的事务管理器实现可能也提供了同样的功能。使用PROPAGATION_NESTED,还需要把PlatformTransactionManager的nestedTransactionAllowed属性设为true;而 nestedTransactionAllowed属性值默认为false;

Java代码:

 1 //事务属性 PROPAGATION_REQUIRED 
 2 methodA(){ 
 3    doSomeThingA(); 
 4    methodB(); 
 5    doSomeThingB(); 
 6 }
 7 
 8 //事务属性 PROPAGATION_NESTED 
 9 methodB(){ 
10   …… 
11 }

 

如果单独调用methodB方法,则按REQUIRED属性执行。如果调用methodA方法,相当于下面的效果:

Java代码:

 1 main(){ 
 2     Connection con = null; 
 3     Savepoint savepoint = null; 
 4     try{ 
 5       con = getConnection(); 
 6        con.setAutoCommit(false); 
 7        doSomeThingA(); 
 8        savepoint = con2.setSavepoint(); 
 9        try{ 
10       methodB(); 
11        }catch(RuntimeException ex){ 
12         con.rollback(savepoint); 
13        }
14        finally{ 
15         //释放资源 
16       }
17 
18        doSomeThingB(); 
19        con.commit(); 
20     }
21     catch(RuntimeException ex){ 
22       con.rollback(); 
23     }
24     finally{ 
25       //释放资源 
26     }
27 }

 

当methodB方法调用之前,调用setSavepoint方法,保存当前的状态到savepoint。如果methodB方法调用失败,则恢复到之前保存的状态。但是需要注意的是,这时的事务并没有进行提交,如果后续的代码(doSomeThingB()方法)调用失败,则回滚包括methodB方法的所有操作。


嵌套事务一个非常重要的概念就是内层事务依赖于外层事务。外层事务失败时,会回滚内层事务所做的动作。而内层事务操作失败并不会引起外层事务的回滚。


PROPAGATION_NESTED 与PROPAGATION_REQUIRES_NEW的区别:它们非常类似,都像一个嵌套事务,如果不存在一个活动的事务,都会开启一个新的事务。使用 PROPAGATION_REQUIRES_NEW时,内层事务与外层事务就像两个独立的事务一样,一旦内层事务进行了提交后,外层事务不能对其进行回滚。两个事务互不影响。两个事务不是一个真正的嵌套事务。同时它需要JTA事务管理器的支持。


使用PROPAGATION_NESTED时,外层事务的回滚可以引起内层事务的回滚。而内层事务的异常并不会导致外层事务的回滚,它是一个真正的嵌套事务。DataSourceTransactionManager使用savepoint支持PROPAGATION_NESTED时,需要JDBC 3.0以上驱动及1.4以上的JDK版本支持。其它的JTA TrasactionManager实现可能有不同的支持方式。


PROPAGATION_REQUIRES_NEW 启动一个新的, 不依赖于环境的 "内部" 事务. 这个事务将被完全 commited 或 rolled back 而不依赖于外部事务, 它拥有自己的隔离范围, 自己的锁, 等等. 当内部事务开始执行时, 外部事务将被挂起, 内务事务结束时, 外部事务将继续执行。


另一方面, PROPAGATION_NESTED 开始一个 "嵌套的" 事务,  它是已经存在事务的一个真正的子事务. 潜套事务开始执行时,  它将取得一个 savepoint. 如果这个嵌套事务失败, 我们将回滚到此 savepoint. 潜套事务是外部事务的一部分, 只有外部事务结束后它才会被提交。


由此可见, PROPAGATION_REQUIRES_NEW 和 PROPAGATION_NESTED 的最大区别在于, PROPAGATION_REQUIRES_NEW 完全是一个新的事务, 而 PROPAGATION_NESTED 则是外部事务的子事务, 如果外部事务 commit, 潜套事务也会被 commit, 这个规则同样适用于 roll back. 
PROPAGATION_REQUIRED应该是我们首先的事务传播行为。它能够满足我们大多数的事务需求。

posted @ 2014-09-30 13:08  LeonGo  阅读(240)  评论(0编辑  收藏  举报