spring事务的传播性

1、事务的传播性

研究的是多个事务存在时的处理策略
1)REQUIRED:如果存在一个事务,则支持当前事务,如果当前没有事务,就新建一个事务。这是最常见的选择。

2)SUPPORTS:如果存在一个事务,支持当前事务,如果当前没有事务,就以非事务方式执行。

3)MANDATORY:如果存在一个事务,支持当前事务,如果当前没有事务,就抛出异常。

4)REQUIRES_NEW:新建事务,如果当前存在事务,把当前事务挂起。

5)NOT_SUPPORTED:以非事务方式执行操作,如果当前存在事务,就把当前事务挂起。

6)NEVER:以非事务方式执行,如果当前存在事务,则抛出异常。

7)NESTED:支持当前事务,新增Savepoint点,与当前事务同步提交或回滚。

2、测试前准备

2.1、准备好数据库表

数据库transaction_propagation
账号表account、书本表book、库存表book_stock

SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;

-- ----------------------------
-- Table structure for account
-- ----------------------------
DROP TABLE IF EXISTS `account`;
CREATE TABLE `account`  (
  `user_id` int(11) NOT NULL AUTO_INCREMENT,
  `user_name` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL,
  `balance` double(11, 2) UNSIGNED NULL DEFAULT NULL,
  PRIMARY KEY (`user_id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 2 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci ROW_FORMAT = Dynamic STORAGE MEMORY;

-- ----------------------------
-- Records of account
-- ----------------------------
INSERT INTO `account` VALUES (1, 'Albert', 100.00);

-- ----------------------------
-- Table structure for book
-- ----------------------------
DROP TABLE IF EXISTS `book`;
CREATE TABLE `book`  (
  `book_id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL,
  `price` double(11, 2) UNSIGNED NULL DEFAULT NULL,
  PRIMARY KEY (`book_id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 1003 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci ROW_FORMAT = Dynamic;

-- ----------------------------
-- Records of book
-- ----------------------------
INSERT INTO `book` VALUES (1001, '基础数据结构', 60.00);
INSERT INTO `book` VALUES (1002, '数据库设计', 50.00);

-- ----------------------------
-- Table structure for book_stock
-- ----------------------------
DROP TABLE IF EXISTS `book_stock`;
CREATE TABLE `book_stock`  (
  `book_id` int(11) NOT NULL AUTO_INCREMENT,
  `stock` int(11) UNSIGNED NULL DEFAULT NULL,
  PRIMARY KEY (`book_id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 1003 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci ROW_FORMAT = Dynamic;

-- ----------------------------
-- Records of book_stock
-- ----------------------------
INSERT INTO `book_stock` VALUES (1001, 100);
INSERT INTO `book_stock` VALUES (1002, 100);

SET FOREIGN_KEY_CHECKS = 1;

2.2、初始化spring项目

导入一些基本依赖包:jdbc、mysql驱动包、测试模块;

<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

2.3、数据库连接信息配置

#jdbc
spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost/transaction_propagation?useUnicode=true&characterEncoding=utf-8
    username: root
    password: 123456

2.4、Service、Dao

这里只使用测试调用,省略controller以及entity等层构;

1、首先Dao类,编写一个购买的简单操作:查询单价、更新库存、更新账户余额;

@Repository
public class BookShopDao {

    @Autowired
    private JdbcTemplate jdbcTemplate = new JdbcTemplate();

    public double getPriceById(Integer bookId) {
        String sql = "SELECT price FROM BOOK WHERE book_id = ?";
        double price = jdbcTemplate.query(sql, new PreparedStatementSetter() {
            @Override
            public void setValues(PreparedStatement preparedStatement) throws SQLException {
                preparedStatement.setInt(1, bookId);
            }
        }, new ResultSetExtractor<Double>() {
            @Override
            public Double extractData(ResultSet resultSet) throws SQLException, DataAccessException {
                double p = 0.0;
                while (resultSet.next()) {
                    p = resultSet.getDouble("price");
                }
                return p;
            }
        });
        return price;
    }

    public void updateBookStock(Integer bookId, int num) {
        String sql = "UPDATE book_stock SET stock = stock - ? WHERE book_id = ?";
        jdbcTemplate.update(sql, new PreparedStatementSetter() {
            @Override
            public void setValues(PreparedStatement preparedStatement) throws SQLException {
                preparedStatement.setInt(1, num);
                preparedStatement.setInt(2, bookId);
            }
        });

    }

    public void updateBalance(Integer userId, double balance) {
        //修改金额
        String sql = "UPDATE account SET balance = balance - ? WHERE user_id = ?";
        jdbcTemplate.update(sql, new PreparedStatementSetter() {
            @Override
            public void setValues(PreparedStatement preparedStatement) throws SQLException {
                preparedStatement.setDouble(1, balance);
                preparedStatement.setInt(2, userId);
            }
        });
    }
}

2、研究事务传播学性其实就是研究两个以上的事务在嵌套时的应用方式,所以这里需要写两个Service进行嵌套调用;接口类此处省略
BookShopServiceImpl 中的purchase用@Transactional是指一个购买单进来必须保证(1、2、3)的原子性;

@Service
public class BookShopServiceImpl implements BookShopService {

    @Autowired
    private BookShopDao bookShopDao;

    @Transactional
    @Override
    public void purchase(Integer userId,Integer bookId,int num){

        //1、获取要购买的图书价格
        double price = bookShopDao.getPriceById(bookId);
        //2、更新图书库存
        bookShopDao.updateBookStock(bookId,num);

        //3、更新用户余额
        bookShopDao.updateBalance(userId,price*num);
    }
}

CashierServiceImpl 中buy方法中的@Transactional是指一个订单中出现多个购买单进来必须保证的原子性;
因为一个订单可能包含几种商品的购买。

@Service
public class CashierServiceImpl implements CashierService {

    @Autowired
    private BookShopService bookShopService;


    @Transactional
    @Override
    public void buy(List<Map<String,Object>> buys){
        for (Map map : buys){
            //购买
            bookShopService.purchase((Integer) map.get("userId"),(Integer)map.get("bookId"),(int)map.get("num"));
        }
    }
}

2.5、测试类

@SpringBootTest
public class TestBuy {

    @Autowired
    private CashierService cashierService;

    @Test
    void testBookShop(){
        List<Map<String,Object>> list = new ArrayList<>();
        Map<String,Object> map = new HashMap<>();
        map.put("userId",1);
        map.put("bookId",1001);
        map.put("num",1);
        list.add(map);
        map = new HashMap<>();
        map.put("userId",1);
        map.put("bookId",1002);
        map.put("num",1);
        list.add(map);
        try {
            cashierService.buy(list);
        }catch (Exception e){
            e.printStackTrace();
        }

        System.out.println("购买成功!");
    }
}

2.6、说明

以上是使用spring默认的事务传播:REQUIRED,purchase使用同一个事务提交。那就会出现这样的问题:账户上有100块钱,现在提交订单是买一本60块钱的《基础数据结构》以及一本50块钱的《数据库设计》;那么订单总金额是110元,显然账户上余额是不足够购买的,在第一次事务购买60块钱的《基础数据结构》是成功的,但再提交50块钱的《数据库设计》的时候就会抛出异常,那这时在CashierServiceImpl 的外层事务中就会异常并回滚。

3、使用其他传播性

3.1、REQUIRES_NEW

在purchase事务中声明(propagation = Propagation.REQUIRES_NEW);那么在每一次调用purchase时都会开启一个新的事务去提交;那么此时进行购买测试结果:第一本书就会购买成功,第二本书购买失败;因为异常回滚的是第二次调用的purchase事务。

@Transactional(propagation = Propagation.REQUIRES_NEW)
    @Override
    public void purchase(Integer userId,Integer bookId,int num){

        //1、获取要购买的图书价格
        double price = bookShopDao.getPriceById(bookId);
        //2、更新图书库存
        bookShopDao.updateBookStock(bookId,num);

        //3、更新用户余额
        bookShopDao.updateBalance(userId,price*num);
    }

3.2、MANDATORY

会强制要求一个事务提交,否则抛出异常,测试结果与REQUIRED一样,回滚整个订单。

@Transactional(propagation = Propagation.MANDATORY)
    @Override
    public void purchase(Integer userId,Integer bookId,int num){

        //1、获取要购买的图书价格
        double price = bookShopDao.getPriceById(bookId);
        //2、更新图书库存
        bookShopDao.updateBookStock(bookId,num);

        //3、更新用户余额
        bookShopDao.updateBalance(userId,price*num);
    }

如果外层没有事务就抛出异常
** No existing transaction found for transaction marked with propagation ‘mandatory’**

3.3、SUPPORTS

如果外层存在事务则以事务提交,测试结果与REQUIRED一样,回滚整个订单。

@Transactional(propagation = Propagation.SUPPORTS)
    @Override
    public void purchase(Integer userId,Integer bookId,int num){

        //1、获取要购买的图书价格
        double price = bookShopDao.getPriceById(bookId);
        //2、更新图书库存
        bookShopDao.updateBookStock(bookId,num);

        //3、更新用户余额
        bookShopDao.updateBalance(userId,price*num);
    }

如果外层不存在事务,则不以事务提交,将可以成功购买一本书;

3.4、NOT_SUPPORTED

以非事务方式执行操作,如果当前存在事务,就把当前事务挂起。即外层是否有事务都不会影响结果:有一本书可购买成功。

@Transactional(propagation = Propagation.NOT_SUPPORTED)
    @Override
    public void purchase(Integer userId,Integer bookId,int num){

        //1、获取要购买的图书价格
        double price = bookShopDao.getPriceById(bookId);
        //2、更新图书库存
        bookShopDao.updateBookStock(bookId,num);

        //3、更新用户余额
        bookShopDao.updateBalance(userId,price*num);
    }

3.5、NEVER

强制要求不能存在事务,否则抛出异常

@Transactional(propagation = Propagation.NEVER)
    @Override
    public void purchase(Integer userId,Integer bookId,int num){

        //1、获取要购买的图书价格
        double price = bookShopDao.getPriceById(bookId);
        //2、更新图书库存
        bookShopDao.updateBookStock(bookId,num);

        //3、更新用户余额
        bookShopDao.updateBalance(userId,price*num);
    }

存在事务则抛出异常:
Existing transaction found for transaction marked with propagation ‘never’

3.6、NESTED

支持当前事务,新增Savepoint点,与当前事务同步提交或回滚。 结果与REQUIRES一样,回滚整个订单。

@Transactional(propagation = Propagation.NESTED)
    @Override
    public void purchase(Integer userId,Integer bookId,int num){

        //1、获取要购买的图书价格
        double price = bookShopDao.getPriceById(bookId);
        //2、更新图书库存
        bookShopDao.updateBookStock(bookId,num);

        //3、更新用户余额
        bookShopDao.updateBalance(userId,price*num);
    }