您的位置:首页 > 编程语言 > Java开发

Spring 事务的配置和使用详解(包括手动对事务的控制部分)

2017-01-05 20:14 585 查看
最近项目中用到了spring的注解类的事务管理,所以特地学习和记录一下spring的配置和使用。项目中使用的是springMVC + mybatis + mysql。spring的版本是
4.3.0.RELEASE


1. spring 注解事务的配置

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



(1)spring+mybatis 事务配置

xml配置文件的命名空间的引用:如下斜体所示:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
*xmlns:tx="http://www.springframework.org/schema/tx"* xmlns:p="http://www.springframework.org/schema/p"
xmlns:util="http://www.springframework.org/schema/util" xmlns:jdbc="http://www.springframework.org/schema/jdbc"
xmlns:cache="http://www.springframework.org/schema/cache"
xsi:schemaLocation="http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd *http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd* http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc.xsd http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd">[/code] 
<!-- 注册事务管理类 -->
<bean id="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean>

<!-- 开启事务行为 -->
<tx:annotation-driven transaction-manager="transactionManager" />


(2)Spring+hibernate

<!-- 事务管理器配置,单数据源事务 -->
<bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>

<!-- 使用annotation定义事务 -->
<tx:annotation-driven  transaction-manager="transactionManager"   proxy-target-class="true" />


注:根据使用不同的orm框架,事务管理器就不同。使用mybatis使用:

org.springframework.jdbc.datasource.DataSourceTransactionManager


而使用hibernate,则事务管理器类为:

org.springframework.orm.hibernate3.HibernateTransactionManager


事务的传播性、隔离性级别一般设置在service层。

2.spring事务的传播性、隔离性。

@Transactional

(1)这里说明一下,有的把这个注解放在类名称上面了,这样你配置的这个@Transactional 对这个类中的所有public方法都起作用.

(2)@Transactional 方法方法名上,只对这个方法有作用,同样必须是public的方法

我们在使用Spring声明式事务时,有一个非常重要的概念就是事务的属性。事务属性通常由事务的传播行为、事务的隔离级别、事务的超时值和事务的只读标识组成。我们在进行事务划分时,需要进行事务定义,也就是配置事务的属性。

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

TransactionDefinition
public interface TransactionDefinition {
int getPropagationBehavior();
int getIsolationLevel();
int getTimeout();
boolean isReadOnly();
}


getTimeout()方法,它返回事务必须在多少秒内完成。

isReadOnly(
4000
),事务是否只读,事务管理器能够根据这个返回值进行优化,确保事务是只读的。

getIsolationLevel()方法返回事务的隔离级别,事务管理器根据它来控制另外一个事务可以看到本事务内的哪些数据。

一。事务的隔离级别

在TransactionDefinition接口中定义了五个不同的事务隔离级别 :

(a) ISOLATION_DEFAULT:(PlatfromTransactionManager的)默认的隔离级别。使用数据库默认的事务隔离级别.另外四个与JDBC的隔离级别相对应 。

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

例如:

Mary的原工资为1000,财务人员将Mary的工资改为了8000,但未提交事务

Connection con1 = getConnection();
con.setAutoCommit(false);
update employee set salary = 8000 where empId ="Mary";


与此同时,Mary正在读取自己的工资 。

Connection con2 = getConnection();
select  salary from employee where empId ="Mary";
con2.commit();


Mary发现自己的工资变为了8000,欢天喜地!

而财务发现操作有误,而回滚了事务,Mary的工资又变为了1000 。

//con1
con1.rollback();


像这样,Mary记取的工资数8000是一个脏数据。

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

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

例如:

在事务1中,Mary 读取了自己的工资为1000,操作并没有完成 :

con1 = getConnection();
select salary from employee empId ="Mary";


在事务2中,这时财务人员修改了Mary的工资为2000,并提交了事务.

con2 = getConnection();
update employee set salary = 2000;
con2.commit();


在事务1中,Mary 再次读取自己的工资时,工资变为了2000

//con1
select salary from employee empId ="Mary";


在一个事务中前后两次读取的结果并不致,导致了不可重复读。

使用ISOLATION_REPEATABLE_READ可以避免这种情况发生。

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

目前工资为1000的员工有10人。

事务1,读取所有工资为1000的员工。

con1 = getConnection();
Select * from employee where salary =1000;


共读取10条记录

这时另一个事务向employee表插入了一条员工记录,工资也为1000

con2 = getConnection();
Insert into employee(empId,salary) values("Lili",1000);
con2.commit();


事务1再次读取所有工资为1000的员工

select * from employee where salary =1000;


共读取到了11条记录,这就产生了幻像读。

ISOLATION_SERIALIZABLE能避免这样的情况发生。但是这样也耗费了最大的资源。

getPropagationBehavior()返回事务的传播行为,由是否有一个活动的事务来决定一个事务调用。

二。事务的传播性

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

假如我写了两个service类。名字分别为ServiceA和ServiceB。如下:

@Service("ServiceA")
public class ServiceA {

@Resource(name="ServiceB")
private ServiceB serviceB;

@Transactional(propagation=Propagation.REQUIRED)
public methodA(){
//doSomething
serviceB.methodB();
//doSomething
}
}


@Service("ServiceB")
public class ServiceB {

@Transactional(propagation=Propagation.REQUIRED)
public methodB(){
//doSomething
}
}


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

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

如果单独调用serviceB.methodB方法:

main {
serviceB.methodB();
}


相当于:

Main{
Connection con=null;
try{
con = getConnection();
con.setAutoCommit(false);
//方法调用
methodB();
//提交事务
con.commit();
}Catch(RuntimeException ex){
//回滚事务
con.rollback();
}finally{
//释放资源
closeCon();
}
}


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

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

执行效果相当于:

main{
Connection con = null;
try{
con = getConnection();
methodA();
con.commit();
}cathc(RuntimeException ex){
con.rollback();
}finally{
closeCon();
}
}


调用MethodA时,环境中没有事务,所以开启一个新的事务.

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

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

//事务属性 PROPAGATION_REQUIRED
methodA(){
serviceB.methodB();
}

//事务属性 PROPAGATION_SUPPORTS
methodB(){
……
}


单纯的调用methodB时,methodB方法是非事务的执行的。

当调用methdA时,methodB则加入了methodA的事务中,事务地执行。

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

//事务属性 PROPAGATION_REQUIRED
methodA(){
serviceB.methodB();
}

//事务属性 PROPAGATION_MANDATORY
methodB(){
……
}


当单独调用methodB时,因为当前没有一个活动的事务,则会抛出异常

throw new IllegalTransactionStateException(“Transaction propagation ‘mandatory’ but no existing transaction found”);

当调用methodA时,methodB则加入到methodA的事务中,事务地执行。

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

//事务属性 PROPAGATION_REQUIRED
methodA(){
doSomeThingA();
serviceB.methodB();
doSomeThingB();
}

//事务属性 PROPAGATION_REQUIRES_NEW
methodB(){
……
}


当单独调用methodB时,相当于把methodb声明为REQUIRED。开启一个新的事务,事务地执行。

当调用methodA时:

main(){
methodA();
}


情况就大不一样了,相当于下面的效果。

main(){
TransactionManager tm = null;
try{
//获得一个JTA事务管理器
tm = getTransactionManager();
tm.begin();//开启一个新的事务
Transaction ts1 = tm.getTransaction();
doSomeThing();
tm.suspend();//挂起当前事务
try{
tm.begin();//重新开启第二个事务
Transaction ts2 = tm.getTransaction();
methodB();
ts2.commit();//提交第二个事务

}Catch(RunTimeException ex){
ts2.rollback();//回滚第二个事务
}finally{
//释放资源
}
//methodB执行完后,复恢第一个事务
tm.resume(ts1);
doSomeThingB();
ts1.commit();//提交第一个事务
}catch(RunTimeException ex){
ts1.rollback();//回滚第一个事务
}finally{
//释放资源
}
}


在这里,我把ts1称为外层事务,ts2称为内层事务。从上面的代码可以看出,ts2与ts1是两个独立的事务,互不相干。Ts2是否成功并不依赖于ts1。如果methodA方法在调用methodB方法后的doSomeThingB方法失败了,而methodB方法所做的结果依然被提交。而除了methodB之外的其它代码导致的结果却被回滚了。

使用PROPAGATION_REQUIRES_NEW,需要使用JtaTransactionManager作为事务管理器。

(e)PROPAGATION_NOT_SUPPORTED: 总是非事务地执行,并挂起任何存在的事务。

//事务属性 PROPAGATION_REQUIRED
methodA(){
doSomeThingA();
serviceB.methodB();
doSomeThingB();
}

//事务属性 PROPAGATION_NOT_SUPPORTED
methodB(){
……
}


当单独调用methodB时,不启用任何事务机制,非事务地执行。

当调用methodA时,相当于下面的效果

main(){
TransactionManager tm = null;
try{
//获得一个JTA事务管理器
tm = getTransactionManager();
tm.begin();//开启一个新的事务
Transaction ts1 = tm.getTransaction();
doSomeThing();
tm.suspend();//挂起当前事务
methodB();
//methodB执行完后,复恢第一个事务
tm.resume(ts1);
doSomeThingB();
ts1.commit();//提交第一个事务
}catch(RunTimeException ex){
ts1.rollback();//回滚第一个事务
}finally{
//释放资源
}
}


使用PROPAGATION_NOT_SUPPORTED,也需要使用JtaTransactionManager作为事务管理器。

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

//事务属性 PROPAGATION_REQUIRED
methodA(){
doSomeThingA();
seviceB.methodB();
doSomeThingB();
}

//事务属性 PROPAGATION_NEVER
methodB(){
……
}


单独调用methodB,则非事务的执行。

调用methodA则会抛出异常

throw new IllegalTransactionStateException(

“Transaction propagation ‘never’ but existing transaction found”);

(g)PROPAGATION_NESTED:如果一个活动的事务存在,则运行在一个嵌套的事务中. 如果没有活动事务, 则按TransactionDefinition.PROPAGATION_REQUIRED 属性执行

这是一个嵌套事务,使用JDBC 3.0驱动时,仅仅支持DataSourceTransactionManager作为事务管理器。需要JDBC 驱动的java.sql.Savepoint类。有一些JTA的事务管理器实现可能也提供了同样的功能。

使用PROPAGATION_NESTED,还需要把PlatformTransactionManager的nestedTransactionAllowed属性设为true;

而nestedTransactionAllowed属性值默认为false;

例如如下:

<bean id="system.platformTransactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="system.sessionFactory"/>
<property name="nestedTransactionAllowed" value="true"/>
</bean>


//事务属性 PROPAGATION_REQUIRED
methodA(){
doSomeThingA();
serviceB.methodB();
doSomeThingB();
}

//事务属性 PROPAGATION_NESTED
methodB(){
……
}


如果单独调用methodB方法,则按REQUIRED属性执行。

如果调用methodA方法,相当于下面的效果

main(){
Connection con = null;
Savepoint savepoint = null;
try{
con = getConnection();
con.setAutoCommit(false);
doSomeThingA();
//创造一个事务的保存点
savepoint = con2.setSavepoint();
try
methodB();
}catch(RuntimeException ex){
con.rollback(savepoint);
}
finally{
//释放资源
}

doSomeThingB();
con.commit();
}
catch(RuntimeException ex){
con.rollback();
}
finally{
//释放资源
}
}


当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_REQUIRED应该是我们首先的事务传播行为。它能够满足我们大多数的事务需求。

3。事务的超时性、回滚和只读

超时:

@Transactional(timeout=30) //默认是30秒

异常回滚:

指定单一异常类:@Transactional(rollbackFor=RuntimeException.class)

指定多个异常类:@Transactional(rollbackFor={RuntimeException.class, Exception.class})

该属性用于设置需要进行回滚的异常类数组,当方法中抛出指定异常数组中的异常时,则进行事务回滚。

正常的情况下也可以回滚:

TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();

只读

@Transactional(readOnly=true)

该属性用于设置当前事务是否为只读事务,设置为true表示只读,false则表示可读写,默认值为false。

4。单独创建事务点手动提交

1、配置文件 applicationContext.xml:

<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean>


2、在需要加事务的方法上加上(有ApplicationContext 的情况下):

//这种情况是有ApplicationContext的情况下,即ctx
DataSourceTransactionManager transactionManager = (DataSourceTransactionManager) ctx
.getBean("transactionManager");
DefaultTransactionDefinition def = new DefaultTransactionDefinition();
def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); // 事物隔离级别,开启新事务,这样会比较安全些。
TransactionStatus status = transactionManager.getTransaction(def); // 获得事务状态
try {
//逻辑代码,可以写上你的逻辑处理代码
transactionManager.commit(status);
} catch (Exception e) {
transactionManager.rollback(status);
}


上面是有ApplicationContext 的情况下。

3、ApplicationContext 不存在的情况下:

//可以通过注解实现
@Autowired
private DataSourceTransactionManager txManager;
DefaultTransactionDefinition def = new DefaultTransactionDefinition();
def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);// 事物隔离级别,开启新事务
TransactionStatus status = txManager.getTransaction(def); // 获得事务状态
try{
//逻辑代码,可以写上你的逻辑处理代码
txManager.commit(status);
}catch(Exception
e){
txManager.rollback(status);
}


参考:详解spring事务属性

Spring事务配置的五种方式

关于Spring事务传播级别PROPAGATION_NESTED的问题

SpringMVC 手动控制事务提交
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息