什么事务传播机制
首先这个传播机制跟数据库是没有关系的,不会因为你是Mysql或者oracle而有所区别。它是Spring框架中提供的一种事务增强机制,合理的利用能很好的解决一些方法之间的嵌套问题,如果不清楚很可能导致各种奇怪的问题。
事务传播机制的类型
在Spring中一共提供了七种事务传播机制,在TransactionDefinition中可以找到如下表的定义:
事务传播类型 | 说明 |
---|---|
PROPAGATION_REQUIRED | 如果当前没有事务,则创建一个新的事务。如果存在事务,则加入到该事务。这是我们用的最多的一种,同时也是Spring框架默认的。 |
PROPAGATION_SUPPORTS | 支持事务运行,如果当前有事务则加入,没有则以非事务的方式运行。 |
PROPAGATION_MANDATORY | 使用当前事务运行,如果当前没有事务,则抛出异常。 |
PROPAGATION_REQUIRES_NEW | 新建事务,如果当前以及存在事务,则把当前事务挂起。 |
PROPAGATION_NOT_SUPPORTED | 已非事务的方式运行,如果当前存在事务,则挂起当前事务。 |
PROPAGATION_NEVER | 不支持事务,已非事务的方式运行。如果当前存在事务,则抛出异常。 |
PROPAGATION_NESTED | 如果当前存在事务,则嵌套在该事务内执行。如果不存在事务,则与PROPAGATION_REQUIRED一样执行。 |
上面介绍了Spring框架默认提供的七种事务传播机制,下面我们通过代码来演示不同事务机制下的运行结果。
下面的代码中我们在AuthorServiceImpl调用BookServiceImpl中的方法,然后通过Spring的事务日志中查看事务相关信息。
logging.level.org.springframework.jdbc=debug
通过在properties配置文件中设置日志打印级别,我们可以看到Spring完整的事务信息。
AuthorServiceImpl.java
@Service
@Slf4j
public class AuthorServiceImpl implements AuthorService {
@Autowired
private AuthorMapper authorMapper;
@Autowired
private BookService bookService;
@Override
public void addAuthor1() {
Author author = new Author("addAuthor1");
log.info("插入addAuthor1");
authorMapper.insertAuthor(author);
log.info("插入addAuthor1完成");
bookService.insertBook1();
}
@Override
public void addAuthor2() {
Author author = new Author("addAuthor2");
log.info("插入addAuthor2");
authorMapper.insertAuthor(author);
log.info("插入addAuthor2完成");
bookService.insertBook2();
}
@Override
public void addAuthor3() {
Author author = new Author("addAuthor3");
log.info("插入addAuthor3");
authorMapper.insertAuthor(author);
log.info("插入addAuthor3完成");
bookService.insertBook3();
}
@Override
@Transactional(propagation = Propagation.REQUIRED)
public void addAuthor4() {
Author author = new Author("addAuthor4");
log.info("插入addAuthor4");
authorMapper.insertAuthor(author);
log.info("插入addAuthor4完成");
bookService.insertBook4();
}
@Override
@Transactional(propagation = Propagation.REQUIRED)
public void addAuthor5() {
Author author = new Author("addAuthor5");
log.info("插入addAuthor5");
authorMapper.insertAuthor(author);
log.info("插入addAuthor5完成");
bookService.insertBook5();
}
@Override
@Transactional(propagation = Propagation.REQUIRED)
public void addAuthor6() {
Author author = new Author("addAuthor6");
log.info("插入addAuthor6");
authorMapper.insertAuthor(author);
log.info("插入addAuthor6完成");
bookService.insertBook6();
}
@Override
public void addAuthor7() {
Author author = new Author("addAuthor7");
log.info("插入addAuthor7");
authorMapper.insertAuthor(author);
log.info("插入addAuthor7完成");
bookService.insertBook7();
}
}
BookServiceImpl.java
@Service
@Slf4j
public class BookServiceImpl implements BookService {
@Autowired
private BookMapper bookMapper;
/**
* 如果已经存在事务则加入该事务,如果不存在,则新建一个新的事务
*/
@Override
@Transactional(propagation = Propagation.REQUIRED)
public void insertBook1() {
log.info("插入insertBook1");
Book book = new Book("insertBook1");
bookMapper.insertBook(book);
log.info("插入insertBook1完成");
}
/**
* 如果存在事务则加入,不存在则已非事务的方式运行
*/
@Override
@Transactional(propagation = Propagation.SUPPORTS)
public void insertBook2() {
log.info("插入insertBook2");
Book book = new Book("insertBook2");
bookMapper.insertBook(book);
log.info("插入insertBook2完成");
}
/**
* 如果存在事务则加入,不存在直接抛出异常
*/
@Override
@Transactional(propagation = Propagation.MANDATORY)
public void insertBook3() {
log.info("插入insertBook3");
Book book = new Book("insertBook3");
bookMapper.insertBook(book);
log.info("插入insertBook3完成");
}
/**
* 如果存在事务,则挂起当前事务,然后新建事务
*/
@Override
@Transactional(propagation = Propagation.REQUIRES_NEW)
public void insertBook4() {
log.info("插入insertBook4");
Book book = new Book("insertBook4");
bookMapper.insertBook(book);
log.info("插入insertBook4完成");
}
/**
* 如果存在事务,则挂起当前事务,以非事务形式运行
*/
@Override
@Transactional(propagation = Propagation.NOT_SUPPORTED)
public void insertBook5() {
log.info("插入insertBook5");
Book book = new Book("insertBook5");
bookMapper.insertBook(book);
log.info("插入insertBook5完成");
}
/**
* 如果不存在事务,则已非事务形式运行。如果存在事务,则抛出异常
*/
@Override
@Transactional(propagation = Propagation.NEVER)
public void insertBook6() {
log.info("插入insertBook6");
Book book = new Book("insertBook6");
bookMapper.insertBook(book);
log.info("插入insertBook6完成");
}
/**
*
*/
@Override
@Transactional(propagation = Propagation.NESTED)
public void insertBook7() {
log.info("插入insertBook7");
Book book = new Book("insertBook7");
bookMapper.insertBook(book);
log.info("插入insertBook7完成");
}
}
PROPAGATION_REQUIRED
首先我们调用addAuthor1方法,addAuthor1上并没有开启事务,而insertBook1开启事务传播方式设置为REQUIRED,日志信息如下:
插入addAuthor1
Fetching JDBC Connection from DataSource
插入addAuthor1完成
Creating new transaction with name [com.buydeem.share.springtxpropagation.service.impl.BookServiceImpl.insertBook1]: PROPAGATION_REQUIRED,ISOLATION_DEFAULT
Acquired Connection [HikariProxyConnection@2123502254 wrapping com.mysql.cj.jdbc.ConnectionImpl@73a3abfa] for JDBC transaction
Switching JDBC Connection [HikariProxyConnection@2123502254 wrapping com.mysql.cj.jdbc.ConnectionImpl@73a3abfa] to manual commit
插入insertBook1
插入insertBook1完成
Initiating transaction commit
Committing JDBC transaction on Connection [HikariProxyConnection@2123502254 wrapping com.mysql.cj.jdbc.ConnectionImpl@73a3abfa]
Releasing JDBC Connection [HikariProxyConnection@2123502254 wrapping com.mysql.cj.jdbc.ConnectionImpl@73a3abfa] after transaction
从日志1-3行可以看出,addAuthor1并没有开启事务,而日志的4-11行分别经历了开启事务,执行插入SQL,然后提交事务这么一个过程。
PROPAGATION_SUPPORTS
首先我们调用addAuthor2方法,addAuthor2上并没有开启事务,而insertBook2开启事务,传播类型设置为SUPPORTS,日志信息如下:
插入addAuthor2
Fetching JDBC Connection from DataSource
插入addAuthor2完成
插入insertBook2
Fetching JDBC Connection from DataSource
插入insertBook2完成
从上面的日志可以看出,整个过程都没有开启事务,因为在addAuthor2方法上并没有开启事务,所以insertBook2则已非事务的方式运行。
PROPAGATION_MANDATORY
首先我们调用addAuthor3方法,addAuthor3上并没有开启事务,而insertBook3开启事务,传播类型设置为MANDATORY,日志信息如下:
org.springframework.transaction.IllegalTransactionStateException: No existing transaction found for transaction marked with propagation 'mandatory'
该次方法调用没有完成,而是抛出了异常。问题就在于addAuthor3没有开启日志,insertBook3必须是在有事务的情况下才可以正常运行。
PROPAGATION_REQUIRES_NEW
首先我们调用addAuthor4方法,addAuthor4上开启事务,insertBook4也开启事务,传播类型设置为REQUIRES_NEW,日志信息如下:
Creating new transaction with name [com.buydeem.share.springtxpropagation.service.impl.AuthorServiceImpl.addAuthor4]: PROPAGATION_REQUIRED,ISOLATION_DEFAULT
Acquired Connection [HikariProxyConnection@711616768 wrapping com.mysql.cj.jdbc.ConnectionImpl@73a3abfa] for JDBC transaction
Switching JDBC Connection [HikariProxyConnection@711616768 wrapping com.mysql.cj.jdbc.ConnectionImpl@73a3abfa] to manual commit
插入addAuthor4
插入addAuthor4完成
Suspending current transaction, creating new transaction with name [com.buydeem.share.springtxpropagation.service.impl.BookServiceImpl.insertBook4]
Acquired Connection [HikariProxyConnection@1421806083 wrapping com.mysql.cj.jdbc.ConnectionImpl@648e1366] for JDBC transaction
Switching JDBC Connection [HikariProxyConnection@1421806083 wrapping com.mysql.cj.jdbc.ConnectionImpl@648e1366] to manual commit
插入insertBook4
插入insertBook4完成
Initiating transaction commit
Committing JDBC transaction on Connection [HikariProxyConnection@1421806083 wrapping com.mysql.cj.jdbc.ConnectionImpl@648e1366]
Releasing JDBC Connection [HikariProxyConnection@1421806083 wrapping com.mysql.cj.jdbc.ConnectionImpl@648e1366] after transaction
Resuming suspended transaction after completion of inner transaction
Initiating transaction commit
Committing JDBC transaction on Connection [HikariProxyConnection@711616768 wrapping com.mysql.cj.jdbc.ConnectionImpl@73a3abfa]
Releasing JDBC Connection [HikariProxyConnection@711616768 wrapping com.mysql.cj.jdbc.ConnectionImpl@73a3abfa] after transaction
从日志1-5行可以看出,在执行addAuthor4方法时开启了事务。6-13行可以看出在执行insertBook4方法时开启了事务,在Sql执行完成之后提交了事务。14-17行可以看出它恢复了addAuthor4开启的事务并提交了事务,所以在该次方法调用中实际上是开启了两个事务。
PROPAGATION_NOT_SUPPORTED
首先我们调用addAuthor5方法,addAuthor5上开启事务,insertBook5也开启事务,传播类型设置为NOT_SUPPORTED,日志信息如下:
Creating new transaction with name [com.buydeem.share.springtxpropagation.service.impl.AuthorServiceImpl.addAuthor5]: PROPAGATION_REQUIRED,ISOLATION_DEFAULT
Acquired Connection [HikariProxyConnection@1147713578 wrapping com.mysql.cj.jdbc.ConnectionImpl@73a3abfa] for JDBC transaction
Switching JDBC Connection [HikariProxyConnection@1147713578 wrapping com.mysql.cj.jdbc.ConnectionImpl@73a3abfa] to manual commit
插入addAuthor5
插入addAuthor5完成
Suspending current transaction
插入insertBook5
Fetching JDBC Connection from DataSource
插入insertBook5完成
Resuming suspended transaction after completion of inner transaction
Initiating transaction commit
Committing JDBC transaction on Connection [HikariProxyConnection@1147713578 wrapping com.mysql.cj.jdbc.ConnectionImpl@73a3abfa]
Releasing JDBC Connection [HikariProxyConnection@1147713578 wrapping com.mysql.cj.jdbc.ConnectionImpl@73a3abfa] after transaction
从日志的1-5行可以看出,方法addAuthor5开启了事务并执行了SQL,在6-9行可以看出,insertBook5并没有开启新的事务,而是暂停了之前的事务以非事务的方式运行。在日志的10-13行可以看出,它恢复了之前暂停的事务然后提交了事务。
PROPAGATION_NEVER
首先我们调用addAuthor6方法,addAuthor6上开启事务,insertBook6也开启事务,传播类型设置为NEVER,日志信息如下:
org.springframework.transaction.IllegalTransactionStateException: Existing transaction found for transaction marked with propagation 'never'
该方法并没有完整的执行完成,而是在抛出了异常。这是因为在addAuthor6中开启了事务,而insertBook6设置的传播类型为PROPAGATION_NEVER,从异常信息也能看出。
PROPAGATION_NESTED
该方式比较特殊,意思是在已存在的事务中再次开启事务,即事务的嵌套。在其他数据库中暂时未做测试,在Mysql中并不是在事务中再开启一个子事务,而是提供一个savepoint,类似于一个暂存档。如果在事务中再次使用start transaction/begin,这将会导致前一个事务并隐式提交。该传播模式对应到Mysql如下所示:
mysql> begin;
Query OK, 0 rows affected
mysql> insert into t_book (book_name) value ('test1');
Query OK, 1 row affected
mysql> savepoint s1;
Query OK, 0 rows affected
mysql> insert into t_book (book_name) value ('test2');
Query OK, 1 row affected
mysql> commit;
Query OK, 0 rows affected
mysql> select * from t_book;
+----+-------------+
| id | book_name |
+----+-------------+
| 19 | test1 |
+----+-------------+
1 rows in set
首先我们调用addAuthor7方法,addAuthor7上开启事务,insertBook7也开启事务,传播类型设置为NESTED,日志信息如下:
Creating new transaction with name [com.buydeem.share.springtxpropagation.service.impl.AuthorServiceImpl.addAuthor7]: PROPAGATION_REQUIRED,ISOLATION_DEFAULT
Acquired Connection [HikariProxyConnection@1072851271 wrapping com.mysql.cj.jdbc.ConnectionImpl@25e98b3f] for JDBC transaction
Switching JDBC Connection [HikariProxyConnection@1072851271 wrapping com.mysql.cj.jdbc.ConnectionImpl@25e98b3f] to manual commit
插入addAuthor7
插入addAuthor7完成
Creating nested transaction with name [com.buydeem.share.springtxpropagation.service.impl.BookServiceImpl.insertBook7]
插入insertBook7
插入insertBook7完成
Releasing transaction savepoint
Initiating transaction commit
Committing JDBC transaction on Connection [HikariProxyConnection@1072851271 wrapping com.mysql.cj.jdbc.ConnectionImpl@25e98b3f]
Releasing JDBC Connection [HikariProxyConnection@1072851271 wrapping com.mysql.cj.jdbc.ConnectionImpl@25e98b3f] after transaction
从日志的1-5行可以看出,addAuthor7开启了一个事务。从6-9可以看出,insertBook7创建了一个嵌套事务,并且嵌套事务的名字为:com.buydeem.share.springtxpropagation.service.impl.BookServiceImpl.insertBook7,然后在insertBook7中的sql执行完成之后release了savepoint。在10-12行中可以看出,整个事务被提交了。
事务传播失效
有时候在开发的时候我们很容易会犯一个低级错误,例如下面的代码:
@Override
public void addAuthor8() {
Author author = new Author("addAuthor8");
log.info("插入addAuthor8");
authorMapper.insertAuthor(author);
log.info("插入addAuthor8完成");
addAuthor9();
}
@Override
@Transactional(propagation = Propagation.REQUIRED)
public void addAuthor9() {
Author author = new Author("addAuthor9");
log.info("插入addAuthor9");
authorMapper.insertAuthor(author);
log.info("插入addAuthor9完成");
}
当我们调用addAuthor8时,按照我们前面所讲的事务传播类型来说,addAuthor9应该是会开启事务的。但是实际上从打印的日志中可以看出并非如此:
插入addAuthor8
Fetching JDBC Connection from DataSource
插入addAuthor8完成
插入addAuthor9
Fetching JDBC Connection from DataSource
插入addAuthor9完成
从打印的日志可以看出,整个过程都没有打印出开启事务和事务提交相关信息。造成这个问题的原因就是动态代理造成的。
在Spring中像@Transcation,@Cacheable等注解都是通过AOP的方式来实现的,在AOP的实现过程中就用到了动态代理。当默认情况下,例如在UserServiceImpl类中方法A调用方法B,方法B上的注解将不会生效。要想自调用注解生效有如下几种解决方案:
Autowired注入自身
@Autowired
private AuthorService authorService;
@Override
public void addAuthor10() {
Author author = new Author("addAuthor10");
log.info("插入addAuthor10");
authorMapper.insertAuthor(author);
log.info("插入addAuthor10完成");
authorService.addAuthor9();
}
最后打印的日志如下:
插入addAuthor10
Fetching JDBC Connection from DataSource
插入addAuthor10完成
Creating new transaction with name [com.buydeem.share.springtxpropagation.service.impl.AuthorServiceImpl.addAuthor9]: PROPAGATION_REQUIRED,ISOLATION_DEFAULT
Acquired Connection [HikariProxyConnection@146798052 wrapping com.mysql.cj.jdbc.ConnectionImpl@22010483] for JDBC transaction
Switching JDBC Connection [HikariProxyConnection@146798052 wrapping com.mysql.cj.jdbc.ConnectionImpl@22010483] to manual commit
插入addAuthor9
插入addAuthor9完成
Initiating transaction commit
Committing JDBC transaction on Connection [HikariProxyConnection@146798052 wrapping com.mysql.cj.jdbc.ConnectionImpl@22010483]
Releasing JDBC Connection [HikariProxyConnection@146798052 wrapping com.mysql.cj.jdbc.ConnectionImpl@22010483] after transaction
从结果可以看出,事务的传播类型生效了。我们通过将自身注入的本类中,而注入的AuthorService是动态代理生成的代理类,而不是没有经过加强的被代理类,所以上面的@Transcation注解才会生效。不过这种方式看上去比较奇怪,不过他确实是能工作,因为Spring已经解决了这种循环依赖。
AopContext代替this
@SpringBootApplication
@MapperScan(basePackages = {"com.buydeem.share.springtxpropagation.dao"})
@EnableAspectJAutoProxy(exposeProxy = true)
public class SpringTxPropagationApplication {
public static void main(String[] args) {
SpringApplication.run(SpringTxPropagationApplication.class, args);
}
}
@Override
public void addAuthor11() {
Author author = new Author("addAuthor11");
log.info("插入addAuthor11");
authorMapper.insertAuthor(author);
log.info("插入addAuthor11完成");
AuthorService temp = (AuthorService) AopContext.currentProxy();
temp.addAuthor9();
}
通过AopContext获取当前类的代理对象,该方式需要注意的一点就是添加下面的配置:
@EnableAspectJAutoProxy(exposeProxy = true)
同时在pom.xml文件中添加如下依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
从ApplicationContext中获取实例
@Autowired
private ApplicationContext applicationContext;
@Override
public void addAuthor12() {
Author author = new Author("addAuthor12");
log.info("插入addAuthor12");
authorMapper.insertAuthor(author);
log.info("插入addAuthor12完成");
AuthorService temp = applicationContext.getBean(AuthorService.class);
temp.addAuthor9();
}
上面的方式就是通过ApplicationContext容器中获取AuthorService的代理类,通过该方式同样能解决自调用的AOP不生效的错误。