Spring中的事务
Spring的事务其实就是数据库的事务操作,符合ACID标准,也具有标准的事务隔离级别。
Spring中的事务只是对JDBC事务进行一些封装与扩展,其底层最终还是会使用到JDBC的这套API。但是Spring事务有自己的特点,也就是事务传播机制。
所谓事务传播机制,也就是在事务在多个方法的调用中是如何传递的,是重新创建事务还是使用父方法的事务?父方法的回滚对子方法的事务是否有影响?这些都是可以通过事务传播机制来决定的。
准备工作
实体类
Area
package com.morris.spring.entity;import lombok.Data;import java.io.Serializable;@Datapublic class Area implements Serializable {private Integer id;private String areaName;private Integer areaCode;}
Good
package com.morris.spring.entity;import lombok.Data;import java.io.Serializable;import java.math.BigDecimal;@Datapublic class Good implements Serializable {private Integer id;private String goodName;private BigDecimal price;}
DAO层
AreaDao
package com.morris.spring.dao;import com.morris.spring.entity.Area;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.jdbc.core.JdbcTemplate;public class AreaDao {@Autowiredprivate JdbcTemplate jdbcTemplate;public boolean insert(Area area) {String sql = "insert into t_area(area_name, area_code) values(?,?)";return jdbcTemplate.update(sql, area.getAreaName(), area.getAreaCode()) > 0;}}
GoodDao
package com.morris.spring.dao;import com.morris.spring.entity.Good;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.jdbc.core.JdbcTemplate;public class GoodDao {@Autowiredprivate JdbcTemplate jdbcTemplate;public boolean insert(Good good) {String sql = "insert into t_good(good_name, price) values(?,?)";return jdbcTemplate.update(sql, good.getGoodName(), good.getPrice()) > 0;}}
Service层
AreaServiceImpl
package com.morris.spring.service;import com.morris.spring.dao.AreaDao;import com.morris.spring.entity.Area;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.transaction.annotation.Propagation;import org.springframework.transaction.annotation.Transactional;public class AreaServiceImpl implements AreaService {@Autowiredprivate AreaDao areaDao;@Transactional(propagation = Propagation.REQUIRED)@Overridepublic boolean addArea(int i) {int y = 1000000 / i;Area area = new Area();area.setAreaCode(y);area.setAreaName("shenzhen");return areaDao.insert(area);}}
GoodServiceImpl
package com.morris.spring.service;import com.morris.spring.dao.GoodDao;import com.morris.spring.entity.Good;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.transaction.annotation.Propagation;import org.springframework.transaction.annotation.Transactional;import java.math.BigDecimal;public class GoodServiceImpl implements GoodService {@Autowiredprivate GoodDao goodDao;@Transactional(propagation = Propagation.REQUIRED)@Overridepublic boolean addGood() {Good good = new Good();good.setGoodName("iphone");good.setPrice(BigDecimal.valueOf(99999));return goodDao.insert(good);}}
TransactionService
package com.morris.spring.service;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Component;import org.springframework.transaction.annotation.Propagation;import org.springframework.transaction.annotation.Transactional;@Componentpublic class TransactionService {@Autowiredprivate GoodService goodService;@Autowiredprivate AreaService areaService;@Transactional(propagation = Propagation.REQUIRED)public void addGoodAndArea() {System.out.println("------addGoodAndArea-------");areaService.addArea(10);goodService.addGood();}}
测试类
TransactionPropagationDemo
package com.morris.spring.demo.jdbc;import com.morris.spring.config.JdbcConfig;import com.morris.spring.dao.AreaDao;import com.morris.spring.dao.GoodDao;import com.morris.spring.service.AreaServiceImpl;import com.morris.spring.service.GoodServiceImpl;import com.morris.spring.service.TransactionService;import org.junit.jupiter.api.Test;import org.springframework.context.annotation.AnnotationConfigApplicationContext;public class TransactionPropagationDemo {@Testpublic void test() {AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext();applicationContext.register(GoodDao.class);applicationContext.register(AreaDao.class);applicationContext.register(GoodServiceImpl.class);applicationContext.register(AreaServiceImpl.class);applicationContext.register(JdbcConfig.class);applicationContext.register(TransactionService.class);applicationContext.refresh();TransactionService transactionService = applicationContext.getBean(TransactionService.class);transactionService.addGoodAndArea();}}
传播机制
具体选项可以参考枚举类org.springframework.transaction.annotation.Propagation。
选项 | 说明 |
REQUIRED | 默认选项。如果当前没有事务,就新建一个事务,如果已经存在一个事务中,加入到这个事务中。 |
SUPPORTS | 支持当前事务,如果当前没有事务,就以非事务方式执行。 |
MANDATORY | 使用当前的事务,如果当前没有事务,就抛出异常。 |
REQUIRES_NEW | 新建事务,如果当前存在事务,把当前事务挂起。 |
NOT_SUPPORTED | 以非事务方式执行操作,如果当前存在事务,就把当前事务挂起。 |
NEVER | 以非事务方式执行,如果当前存在事务,则抛出异常。 |
NESTED | 如果当前存在事务,则在嵌套事务内执行。如果当前没有事务,则执行与REQUIRED类似的操作。 |
REQUIRED
默认选项。如果当前没有事务,就新建一个事务,如果已经存在一个事务中,加入到这个事务中。
配置如下:
- TransactionService:REQUIRED
- AreaServiceImpl:REQUIRED
- GoodServiceImpl:REQUIRED
运行上面的Demo,运行结果如下:
// 创建第一个事务
DEBUG DataSourceTransactionManager:381 - Creating new transaction with name [com.morris.spring.service.TransactionService.addGoodAndArea]: PROPAGATION_REQUIRED,ISOLATION_DEFAULT
// 创建第一个连接
DEBUG DriverManagerDataSource:144 - Creating new JDBC DriverManager Connection to [jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&allowMultiQueries=true&characterEncoding=UTF-8&useFastDateParsing=false&zeroDateTimeBehavior=convertToNull]
DEBUG DataSourceTransactionManager:265 - Acquired Connection [com.mysql.cj.jdbc.ConnectionImpl@8ef162] for JDBC transaction
DEBUG DataSourceTransactionManager:283 - Switching JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@8ef162] to manual commit
------addGoodAndArea-------
// 在第一个事务中执行
DEBUG DataSourceTransactionManager:487 - Participating in existing transaction
DEBUG JdbcTemplate:860 - Executing prepared SQL update
DEBUG JdbcTemplate:609 - Executing prepared SQL statement [insert into t_good(good_name, price) values(?,?)]
// 在第一个事务中执行
DEBUG DataSourceTransactionManager:487 - Participating in existing transaction
DEBUG JdbcTemplate:860 - Executing prepared SQL update
DEBUG JdbcTemplate:609 - Executing prepared SQL statement [insert into t_area(area_name, area_code) values(?,?)]
// 提交第一个事务
DEBUG DataSourceTransactionManager:763 - Initiating transaction commit
DEBUG DataSourceTransactionManager:329 - Committing JDBC transaction on Connection [com.mysql.cj.jdbc.ConnectionImpl@8ef162]
DEBUG DataSourceTransactionManager:390 - Releasing JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@8ef162] after transaction
总结:
- 当外层没有事务的时候,TransactionService.addGoodAndArea()方法执行发现没有事务可用,自己新建事务。
- goodService.addGood()和areaService.addArea()执行时发现已有事务,就使用当前事务执行。
REQUIRES_NEW
新建事务,如果当前存在事务,把当前事务挂起。
配置如下:
- TransactionService:REQUIRED
- GoodServiceImpl:REQUIRES
- AreaServiceImpl:REQUIRES_NEW
运行结果如下:
// 创建第一个事务
DEBUG DataSourceTransactionManager:381 - Creating new transaction with name [com.morris.spring.service.TransactionService.addGoodAndArea]: PROPAGATION_REQUIRED,ISOLATION_DEFAULT
// 创建第一个连接
DEBUG DriverManagerDataSource:144 - Creating new JDBC DriverManager Connection to [jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&allowMultiQueries=true&characterEncoding=UTF-8&useFastDateParsing=false&zeroDateTimeBehavior=convertToNull]
DEBUG DataSourceTransactionManager:265 - Acquired Connection [com.mysql.cj.jdbc.ConnectionImpl@f9aa66] for JDBC transaction
DEBUG DataSourceTransactionManager:283 - Switching JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@f9aa66] to manual commit
------addGoodAndArea-------
// 挂起第一个事务并创建第二个事务
DEBUG DataSourceTransactionManager:446 - Suspending current transaction, creating new transaction with name [com.morris.spring.service.AreaServiceImpl.addArea]
// 创建第二个连接
DEBUG DriverManagerDataSource:144 - Creating new JDBC DriverManager Connection to [jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&allowMultiQueries=true&characterEncoding=UTF-8&useFastDateParsing=false&zeroDateTimeBehavior=convertToNull]
DEBUG DataSourceTransactionManager:265 - Acquired Connection [com.mysql.cj.jdbc.ConnectionImpl@116fc68] for JDBC transaction
DEBUG DataSourceTransactionManager:283 - Switching JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@116fc68] to manual commit
DEBUG JdbcTemplate:860 - Executing prepared SQL update
DEBUG JdbcTemplate:609 - Executing prepared SQL statement [insert into t_area(area_name, area_code) values(?,?)]
// 提交第二个事务
DEBUG DataSourceTransactionManager:763 - Initiating transaction commit
DEBUG DataSourceTransactionManager:329 - Committing JDBC transaction on Connection [com.mysql.cj.jdbc.ConnectionImpl@116fc68]
DEBUG DataSourceTransactionManager:390 - Releasing JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@116fc68] after transaction
// 恢复第一个事务
DEBUG DataSourceTransactionManager:1043 - Resuming suspended transaction after completion of inner transaction
// 在第一个事务中执行
DEBUG DataSourceTransactionManager:487 - Participating in existing transaction
DEBUG JdbcTemplate:860 - Executing prepared SQL update
DEBUG JdbcTemplate:609 - Executing prepared SQL statement [insert into t_good(good_name, price) values(?,?)]
DEBUG DataSourceTransactionManager:763 - Initiating transaction commit
DEBUG DataSourceTransactionManager:329 - Committing JDBC transaction on Connection [com.mysql.cj.jdbc.ConnectionImpl@f9aa66]
DEBUG DataSourceTransactionManager:390 - Releasing JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@f9aa66] after transaction
总结:areaServiceImpl.addArea()执行时发现已有事务,就把当前事务挂起,执行完后再恢复。
SUPPORTS
支持当前事务,如果当前没有事务,就以非事务方式执行。
配置如下:
- TransactionService:SUPPORTS
- AreaServiceImpl:REQUIRED
- GoodServiceImpl:SUPPORTS
运行结果如下:
// TransactionService.addGoodAndArea以非事务方式运行
------addGoodAndArea-------
// 开启第一个事务
DEBUG DataSourceTransactionManager:381 - Creating new transaction with name [com.morris.spring.service.AreaServiceImpl.addArea]: PROPAGATION_REQUIRED,ISOLATION_DEFAULT
// 创建第一个连接
DEBUG DriverManagerDataSource:144 - Creating new JDBC DriverManager Connection to [jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&allowMultiQueries=true&characterEncoding=UTF-8&useFastDateParsing=false&zeroDateTimeBehavior=convertToNull]
DEBUG DataSourceTransactionManager:265 - Acquired Connection [com.mysql.cj.jdbc.ConnectionImpl@1691f3d] for JDBC transaction
DEBUG DataSourceTransactionManager:283 - Switching JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@1691f3d] to manual commit
DEBUG JdbcTemplate:860 - Executing prepared SQL update
DEBUG JdbcTemplate:609 - Executing prepared SQL statement [insert into t_area(area_name, area_code) values(?,?)]
// 提交第一个事务
DEBUG DataSourceTransactionManager:763 - Initiating transaction commit
DEBUG DataSourceTransactionManager:329 - Committing JDBC transaction on Connection [com.mysql.cj.jdbc.ConnectionImpl@1691f3d]
DEBUG DataSourceTransactionManager:390 - Releasing JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@1691f3d] after transaction
DEBUG DataSourceTransactionManager:1043 - Resuming suspended transaction after completion of inner transaction
// AreaServiceImpl.addArea以非事务方式运行
DEBUG JdbcTemplate:860 - Executing prepared SQL update
DEBUG JdbcTemplate:609 - Executing prepared SQL statement [insert into t_good(good_name, price) values(?,?)]
总结:当前没有事务,TransactionService.addGoodAndArea()和AreaServiceImpl.addArea()以非事务方式运行。
修改配置如下:
- TransactionService:REQUIRED
- AreaServiceImpl:SUPPORTS
- GoodServiceImpl:SUPPORTS
运行结果如下:
// 开启第一个事务
DEBUG DataSourceTransactionManager:381 - Creating new transaction with name [com.morris.spring.service.TransactionService.addGoodAndArea]: PROPAGATION_REQUIRED,ISOLATION_DEFAULT
// 创建第一个连接
DEBUG DriverManagerDataSource:144 - Creating new JDBC DriverManager Connection to [jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&allowMultiQueries=true&characterEncoding=UTF-8&useFastDateParsing=false&zeroDateTimeBehavior=convertToNull]
DEBUG DataSourceTransactionManager:265 - Acquired Connection [com.mysql.cj.jdbc.ConnectionImpl@11158fb] for JDBC transaction
DEBUG DataSourceTransactionManager:283 - Switching JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@11158fb] to manual commit
------addGoodAndArea-------
// 在第一个事务中执行
DEBUG DataSourceTransactionManager:487 - Participating in existing transaction
DEBUG JdbcTemplate:860 - Executing prepared SQL update
DEBUG JdbcTemplate:609 - Executing prepared SQL statement [insert into t_area(area_name, area_code) values(?,?)]
// 在第一个事务中执行
DEBUG DataSourceTransactionManager:487 - Participating in existing transaction
DEBUG JdbcTemplate:860 - Executing prepared SQL update
DEBUG JdbcTemplate:609 - Executing prepared SQL statement [insert into t_good(good_name, price) values(?,?)]
// 提交第一个事务
DEBUG DataSourceTransactionManager:763 - Initiating transaction commit
DEBUG DataSourceTransactionManager:329 - Committing JDBC transaction on Connection [com.mysql.cj.jdbc.ConnectionImpl@11158fb]
DEBUG DataSourceTransactionManager:390 - Releasing JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@11158fb] after transaction
总结:当前有事务,GoodServiceImpl.addGood()和AreaServiceImpl.addArea()以事务方式运行。
MANDATORY
使用当前的事务,如果当前没有事务,就抛出异常。
配置如下:
- TransactionService:REQUIRED
- AreaServiceImpl:REQUIRED
- GoodServiceImpl:MANDATORY
运行结果如下:
// 创建第一个事务
EBUG DataSourceTransactionManager:381 - Creating new transaction with name [com.morris.spring.service.TransactionService.addGoodAndArea]: PROPAGATION_REQUIRED,ISOLATION_DEFAULT
// 创建第一个连接
DEBUG DriverManagerDataSource:144 - Creating new JDBC DriverManager Connection to [jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&allowMultiQueries=true&characterEncoding=UTF-8&useFastDateParsing=false&zeroDateTimeBehavior=convertToNull]
DEBUG DataSourceTransactionManager:265 - Acquired Connection [com.mysql.cj.jdbc.ConnectionImpl@11c4a3f] for JDBC transaction
DEBUG DataSourceTransactionManager:283 - Switching JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@11c4a3f] to manual commit
------addGoodAndArea-------
// 在第一个事务中执行
DEBUG DataSourceTransactionManager:487 - Participating in existing transaction
DEBUG JdbcTemplate:860 - Executing prepared SQL update
DEBUG JdbcTemplate:609 - Executing prepared SQL statement [insert into t_area(area_name, area_code) values(?,?)]
// 在第一个事务中执行
DEBUG DataSourceTransactionManager:487 - Participating in existing transaction
DEBUG JdbcTemplate:860 - Executing prepared SQL update
DEBUG JdbcTemplate:609 - Executing prepared SQL statement [insert into t_good(good_name, price) values(?,?)]
// 提交第一个事务
DEBUG DataSourceTransactionManager:763 - Initiating transaction commit
DEBUG DataSourceTransactionManager:329 - Committing JDBC transaction on Connection [com.mysql.cj.jdbc.ConnectionImpl@11c4a3f]
DEBUG DataSourceTransactionManager:390 - Releasing JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@11c4a3f] after transaction
总结:当前有事务,GoodServiceImpl.addGood()以事务方式运行。
修改配置如下:
- TransactionService:SUPPORTS
- AreaServiceImpl:MANDATORY
- GoodServiceImpl:SUPPORTS
运行结果如下:
------addGoodAndArea-------
DEBUG DataSourceTransactionManager:888 - Should roll back transaction but cannot - no transaction available
org.springframework.transaction.IllegalTransactionStateException: No existing transaction found for transaction marked with propagation 'mandatory'
at org.springframework.transaction.support.AbstractPlatformTransactionManager.getTransaction(AbstractPlatformTransactionManager.java:372)
at org.springframework.transaction.interceptor.TransactionAspectSupport.createTransactionIfNecessary(TransactionAspectSupport.java:595)
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:374)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:118)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:205)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:219)
at com.sun.proxy.$Proxy23.addArea(Unknown Source)
at com.morris.spring.service.TransactionService.addGoodAndArea(TransactionService.java:20)
总结:当前没有有事务,AreaServiceImpl.addArea()会抛出异常。
NOT_SUPPORTED
以非事务方式执行操作,如果当前存在事务,就把当前事务挂起。
配置如下:
- TransactionService:REQUIRED
- AreaServiceImpl:NOT_SUPPORTED
- GoodServiceImpl:NOT_SUPPORTED
运行结果如下:
// 开启第一个事务
DEBUG DataSourceTransactionManager:381 - Creating new transaction with name [com.morris.spring.service.TransactionService.addGoodAndArea]: PROPAGATION_REQUIRED,ISOLATION_DEFAULT
DEBUG DriverManagerDataSource:144 - Creating new JDBC DriverManager Connection to [jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&allowMultiQueries=true&characterEncoding=UTF-8&useFastDateParsing=false&zeroDateTimeBehavior=convertToNull]
DEBUG DataSourceTransactionManager:265 - Acquired Connection [com.mysql.cj.jdbc.ConnectionImpl@8ef162] for JDBC transaction
DEBUG DataSourceTransactionManager:283 - Switching JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@8ef162] to manual commit
------addGoodAndArea-------
// 挂起第一个事务
DEBUG DataSourceTransactionManager:436 - Suspending current transaction
// 以非事务方式运行
DEBUG JdbcTemplate:860 - Executing prepared SQL update
DEBUG JdbcTemplate:609 - Executing prepared SQL statement [insert into t_area(area_name, area_code) values(?,?)]
DEBUG DataSourceUtils:115 - Fetching JDBC Connection from DataSource
DEBUG DriverManagerDataSource:144 - Creating new JDBC DriverManager Connection to [jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&allowMultiQueries=true&characterEncoding=UTF-8&useFastDateParsing=false&zeroDateTimeBehavior=convertToNull]
// 恢复第一个事务
DEBUG DataSourceTransactionManager:1043 - Resuming suspended transaction after completion of inner transaction
// 挂起第一个事务
DEBUG DataSourceTransactionManager:436 - Suspending current transaction
// 以非事务方式运行
DEBUG JdbcTemplate:860 - Executing prepared SQL update
DEBUG JdbcTemplate:609 - Executing prepared SQL statement [insert into t_good(good_name, price) values(?,?)]
DEBUG DataSourceUtils:115 - Fetching JDBC Connection from DataSource
DEBUG DriverManagerDataSource:144 - Creating new JDBC DriverManager Connection to [jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&allowMultiQueries=true&characterEncoding=UTF-8&useFastDateParsing=false&zeroDateTimeBehavior=convertToNull]
// 恢复第一个事务
DEBUG DataSourceTransactionManager:1043 - Resuming suspended transaction after completion of inner transaction
// 提交第一个事务
DEBUG DataSourceTransactionManager:763 - Initiating transaction commit
DEBUG DataSourceTransactionManager:329 - Committing JDBC transaction on Connection [com.mysql.cj.jdbc.ConnectionImpl@8ef162]
DEBUG DataSourceTransactionManager:390 - Releasing JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@8ef162] after transaction
总结:执行GoodServiceImpl.addGood()和AreaServiceImpl.addArea()时当前存在事务,就把当前事务挂起。
NEVER
以非事务方式执行,如果当前存在事务,则抛出异常。
配置如下:
- TransactionService:NEVER
- AreaServiceImpl:NEVER
- GoodServiceImpl:NEVER
运行结果如下:
// 没有事务都以非事务方式运行
------addGoodAndArea-------
DEBUG JdbcTemplate:860 - Executing prepared SQL update
DEBUG JdbcTemplate:609 - Executing prepared SQL statement [insert into t_area(area_name, area_code) values(?,?)]
DEBUG DataSourceUtils:115 - Fetching JDBC Connection from DataSource
DEBUG DriverManagerDataSource:144 - Creating new JDBC DriverManager Connection to [jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&allowMultiQueries=true&characterEncoding=UTF-8&useFastDateParsing=false&zeroDateTimeBehavior=convertToNull]
DEBUG JdbcTemplate:860 - Executing prepared SQL update
DEBUG JdbcTemplate:609 - Executing prepared SQL statement [insert into t_good(good_name, price) values(?,?)]
总结:当前没有事务都以非事务方式执行。
修改配置如下:
- TransactionService:REQUIRED
- AreaServiceImpl:NEVER
- GoodServiceImpl:NEVER
运行结果如下:
// 开启第一个事务
DEBUG DataSourceTransactionManager:381 - Creating new transaction with name [com.morris.spring.service.TransactionService.addGoodAndArea]: PROPAGATION_REQUIRED,ISOLATION_DEFAULT
DEBUG DriverManagerDataSource:144 - Creating new JDBC DriverManager Connection to [jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&allowMultiQueries=true&characterEncoding=UTF-8&useFastDateParsing=false&zeroDateTimeBehavior=convertToNull]
DEBUG DataSourceTransactionManager:265 - Acquired Connection [com.mysql.cj.jdbc.ConnectionImpl@8ef162] for JDBC transaction
DEBUG DataSourceTransactionManager:283 - Switching JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@8ef162] to manual commit
------addGoodAndArea-------
DEBUG DataSourceTransactionManager:864 - Initiating transaction rollback
DEBUG DataSourceTransactionManager:345 - Rolling back JDBC transaction on Connection [com.mysql.cj.jdbc.ConnectionImpl@8ef162]
DEBUG DataSourceTransactionManager:390 - Releasing JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@8ef162] after transaction
org.springframework.transaction.IllegalTransactionStateException: Existing transaction found for transaction marked with propagation 'never'
at org.springframework.transaction.support.AbstractPlatformTransactionManager.handleExistingTransaction(AbstractPlatformTransactionManager.java:430)
at org.springframework.transaction.support.AbstractPlatformTransactionManager.getTransaction(AbstractPlatformTransactionManager.java:362)
at org.springframework.transaction.interceptor.TransactionAspectSupport.createTransactionIfNecessary(TransactionAspectSupport.java:595)
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:374)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:118)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:205)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:219)
at com.sun.proxy.$Proxy23.addArea(Unknown Source)
at com.morris.spring.service.TransactionService.addGoodAndArea(TransactionService.java:20)
总结:AreaServiceImpl.addArea()执行时存在事务就会抛出异常。
NESTED
如果当前存在事务,则在嵌套事务内执行。如果当前没有事务,则执行与REQUIRED类似的操作。
配置如下:
- TransactionService:REQUIRED
- GoodServiceImpl:NESTED
- AreaServiceImpl:NESTED
运行结果如下:
// 创建第一个事务
EBUG DataSourceTransactionManager:381 - Creating new transaction with name [com.morris.spring.service.TransactionService.addGoodAndArea]: PROPAGATION_REQUIRED,ISOLATION_DEFAULT
// 创建第一个连接
DEBUG DriverManagerDataSource:144 - Creating new JDBC DriverManager Connection to [jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&allowMultiQueries=true&characterEncoding=UTF-8&useFastDateParsing=false&zeroDateTimeBehavior=convertToNull]
DEBUG DataSourceTransactionManager:265 - Acquired Connection [com.mysql.cj.jdbc.ConnectionImpl@8ef162] for JDBC transaction
DEBUG DataSourceTransactionManager:283 - Switching JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@8ef162] to manual commit
------addGoodAndArea-------
// 创建回滚点
DEBUG DataSourceTransactionManager:466 - Creating nested transaction with name [com.morris.spring.service.AreaServiceImpl.addArea]
DEBUG JdbcTemplate:860 - Executing prepared SQL update
DEBUG JdbcTemplate:609 - Executing prepared SQL statement [insert into t_area(area_name, area_code) values(?,?)]
// 释放回滚点
DEBUG DataSourceTransactionManager:754 - Releasing transaction savepoint
// 创建回滚点
DEBUG DataSourceTransactionManager:466 - Creating nested transaction with name [com.morris.spring.service.GoodServiceImpl.addGood]
DEBUG JdbcTemplate:860 - Executing prepared SQL update
DEBUG JdbcTemplate:609 - Executing prepared SQL statement [insert into t_good(good_name, price) values(?,?)]
// 释放回滚点
DEBUG DataSourceTransactionManager:754 - Releasing transaction savepoint
DEBUG DataSourceTransactionManager:763 - Initiating transaction commit
DEBUG DataSourceTransactionManager:329 - Committing JDBC transaction on Connection [com.mysql.cj.jdbc.ConnectionImpl@8ef162]
DEBUG DataSourceTransactionManager:390 - Releasing JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@8ef162] after transaction
如果不抛出异常,使用REQUIRED与NESTED都差不多,区别在于发生异常,下面演示REQUIRED与NESTED发生异常时的区别:
配置如下:
- TransactionService:REQUIRED
- AreaServiceImpl:REQUIRED
- GoodServiceImpl:REQUIRED
TransactionService.addGoodAndArea修改如下:
@Transactional(propagation = Propagation.REQUIRED)
public void addGoodAndArea() {
System.out.println("------addGoodAndArea-------");
try {
areaService.addArea(0);
} catch (Exception e) {
e.printStackTrace();
}
goodService.addGood();
}
运行结果如下:
DEBUG DataSourceTransactionManager:381 - Creating new transaction with name [com.morris.spring.service.TransactionService.addGoodAndArea]: PROPAGATION_REQUIRED,ISOLATION_DEFAULT
DEBUG DriverManagerDataSource:144 - Creating new JDBC DriverManager Connection to [jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&allowMultiQueries=true&characterEncoding=UTF-8&useFastDateParsing=false&zeroDateTimeBehavior=convertToNull]
DEBUG DataSourceTransactionManager:265 - Acquired Connection [com.mysql.cj.jdbc.ConnectionImpl@f9aa66] for JDBC transaction
DEBUG DataSourceTransactionManager:283 - Switching JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@f9aa66] to manual commit
------addGoodAndArea-------
DEBUG DataSourceTransactionManager:487 - Participating in existing transaction
DEBUG DataSourceTransactionManager:877 - Participating transaction failed - marking existing transaction as rollback-only
DEBUG DataSourceTransactionManager:360 - Setting JDBC transaction [com.mysql.cj.jdbc.ConnectionImpl@f9aa66] rollback-only
java.lang.ArithmeticException: / by zero
at com.morris.spring.service.AreaServiceImpl.addArea(AreaServiceImpl.java:18)
... ...
DEBUG DataSourceTransactionManager:487 - Participating in existing transaction
DEBUG JdbcTemplate:860 - Executing prepared SQL update
DEBUG JdbcTemplate:609 - Executing prepared SQL statement [insert into t_good(good_name, price) values(?,?)]
DEBUG DataSourceTransactionManager:723 - Global transaction is marked as rollback-only but transactional code requested commit
DEBUG DataSourceTransactionManager:877 - Participating transaction failed - marking existing transaction as rollback-only
DEBUG DataSourceTransactionManager:360 - Setting JDBC transaction [com.mysql.cj.jdbc.ConnectionImpl@f9aa66] rollback-only
DEBUG DataSourceTransactionManager:723 - Global transaction is marked as rollback-only but transactional code requested commit
DEBUG DataSourceTransactionManager:864 - Initiating transaction rollback
DEBUG DataSourceTransactionManager:345 - Rolling back JDBC transaction on Connection [com.mysql.cj.jdbc.ConnectionImpl@f9aa66]
DEBUG DataSourceTransactionManager:390 - Releasing JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@f9aa66] after transaction
org.springframework.transaction.UnexpectedRollbackException: Transaction rolled back because it has been marked as rollback-only
at org.springframework.transaction.support.AbstractPlatformTransactionManager.processRollback(AbstractPlatformTransactionManager.java:905)
... ...
从运行结果可以发现事务全部都回滚了。
将上面的配置修改如下:
- TransactionService:REQUIRED
- AreaServiceImpl:NESTED
- GoodServiceImpl:NESTED
运行结果如下:
DEBUG DataSourceTransactionManager:381 - Creating new transaction with name [com.morris.spring.service.TransactionService.addGoodAndArea]: PROPAGATION_REQUIRED,ISOLATION_DEFAULT
DEBUG DriverManagerDataSource:144 - Creating new JDBC DriverManager Connection to [jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&allowMultiQueries=true&characterEncoding=UTF-8&useFastDateParsing=false&zeroDateTimeBehavior=convertToNull]
DEBUG DataSourceTransactionManager:265 - Acquired Connection [com.mysql.cj.jdbc.ConnectionImpl@8ef162] for JDBC transaction
DEBUG DataSourceTransactionManager:283 - Switching JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@8ef162] to manual commit
------addGoodAndArea-------
DEBUG DataSourceTransactionManager:466 - Creating nested transaction with name [com.morris.spring.service.AreaServiceImpl.addArea]
DEBUG DataSourceTransactionManager:857 - Rolling back transaction to savepoint
java.lang.ArithmeticException: / by zero
at com.morris.spring.service.AreaServiceImpl.addArea(AreaServiceImpl.java:18)
... ...
DEBUG DataSourceTransactionManager:466 - Creating nested transaction with name [com.morris.spring.service.GoodServiceImpl.addGood]
DEBUG JdbcTemplate:860 - Executing prepared SQL update
DEBUG JdbcTemplate:609 - Executing prepared SQL statement [insert into t_good(good_name, price) values(?,?)]
DEBUG DataSourceTransactionManager:754 - Releasing transaction savepoint
DEBUG DataSourceTransactionManager:763 - Initiating transaction commit
DEBUG DataSourceTransactionManager:329 - Committing JDBC transaction on Connection [com.mysql.cj.jdbc.ConnectionImpl@8ef162]
DEBUG DataSourceTransactionManager:390 - Releasing JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@8ef162] after transaction
从运行结果可以发现areaService.addArea()回滚了(本来就没有提交内容),goodService.addGood()的内容提交了。
注意只有运行时异常以及rollbakcFor指定的异常才会回滚。
到此这篇关于关于spring中事务的传播机制的文章就介绍到这了,更多相关spring事务的传播机制内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!