黄同学的后端和 Agent 笔记开通
Hello 后端

动手做:复现并修好三种事务没生效

黄同学约 9 分钟读完免费

在 ① 建好的项目 shop 里写一个下单的 Service,故意用四种坏写法:自己调自己、注解贴在 private 方法上、异常被 catch 吞掉、抛受检异常。每调一次,orders 表里都会多出一个没扣库存的订单。然后照事务为什么没生效和哪些异常会回滚一个个修好,直到每次调完 orders 都不多一行。最后顺手验证一个旧说法:protected 方法上的事务到底生不生效。

要先学过:

步骤

  1. 起 MySQL,再执行一遍 lab.sql,让库 shop 回到最初的样子:8 个订单,商品 7 的库存是 10。

    bash
    cd hello-backend
    docker compose up -d --wait
    docker compose exec -T mysql mysql -uroot -psecret --default-character-set=utf8mb4 < lab.sql

    这一页每次都买商品 7 买 999 件,库存只有 10,扣库存一定失败。事务生效的话,订单那一行会跟着回滚,orders 表一行不多。

  2. 打开事务管理器的日志。在 ~/hb-spring/shop/src/main/resources/application.yml 的最后加上:

    yaml
    logging:
      level:
        org.springframework.jdbc.support.JdbcTransactionManager: DEBUG

    logging 顶格写,和 spring、server、mybatis 平级。做过别的节点的动手做页、文件里已经有一个 logging: 的,不要再加一个,把 JdbcTransactionManager 那一行并到原来的 level: 下面,同一个配置项在一个文件里写两次,项目会启动失败。这样每开一个事务、每次提交和回滚,日志里都会有一行,见 @Transactional 怎样生效最后一节。

  3. 这一页的类都放在一个新包 com.shop.txlab 里,和别的节点建的 OrderService 这些类互不影响。先建 Mapper,三句 SQL:插一个订单(金额用商品单价乘件数算)、扣库存、数订单。

    java
    // src/main/java/com/shop/txlab/TxLabMapper.java
    package com.shop.txlab;
    
    import org.apache.ibatis.annotations.Insert;
    import org.apache.ibatis.annotations.Mapper;
    import org.apache.ibatis.annotations.Param;
    import org.apache.ibatis.annotations.Select;
    import org.apache.ibatis.annotations.Update;
    
    @Mapper
    public interface TxLabMapper {
    
        @Insert("INSERT INTO orders (user_id, product_id, quantity, amount, status, created_at) "
                + "SELECT #{userId}, id, #{quantity}, price * #{quantity}, 'UNPAID', NOW() FROM products WHERE id = #{productId}")
        int insertOrder(@Param("userId") Long userId, @Param("productId") Long productId, @Param("quantity") int quantity);
    
        // 库存够才扣,返回改到了几行:0 行就是库存不够
        @Update("UPDATE products SET stock = stock - #{quantity} WHERE id = #{productId} AND stock >= #{quantity}")
        int deductStock(@Param("productId") Long productId, @Param("quantity") int quantity);
    
        @Select("SELECT COUNT(*) FROM orders")
        long countOrders();
    }

    再建一个受检异常,第四种坏写法要用:

    java
    // src/main/java/com/shop/txlab/StockException.java
    package com.shop.txlab;
    
    // 继承 Exception,是受检异常
    public class StockException extends Exception {
        public StockException(String message) {
            super(message);
        }
    }
  4. 写 Service。四个坏方法,外加一个 protected 方法,最后一步用。每个方法都是先插订单、再扣库存:

    java
    // src/main/java/com/shop/txlab/TxLabService.java
    package com.shop.txlab;
    
    import org.springframework.stereotype.Service;
    import org.springframework.transaction.annotation.Transactional;
    
    import lombok.extern.slf4j.Slf4j;
    
    @Slf4j
    @Service
    public class TxLabService {
    
        private final TxLabMapper txLabMapper;
    
        public TxLabService(TxLabMapper txLabMapper) {
            this.txLabMapper = txLabMapper;
        }
    
        // 坏写法一:注解只贴在 deductStock 上,用 this 调它
        public void placeOrderSelfCall(Long userId, Long productId, int quantity) {
            txLabMapper.insertOrder(userId, productId, quantity);
            deductStock(productId, quantity);
        }
    
        @Transactional
        public void deductStock(Long productId, int quantity) {
            if (txLabMapper.deductStock(productId, quantity) == 0) {
                throw new IllegalStateException("库存不足");
            }
        }
    
        // 坏写法二:public 的入口没贴注解,去调一个贴了注解的 private 方法
        public void placeOrderPrivate(Long userId, Long productId, int quantity) {
            doPlace(userId, productId, quantity);
        }
    
        @Transactional
        private void doPlace(Long userId, Long productId, int quantity) {
            txLabMapper.insertOrder(userId, productId, quantity);
            deductStock(productId, quantity);
        }
    
        // 坏写法三:catch 住异常,只记日志
        @Transactional
        public void placeOrderSwallow(Long userId, Long productId, int quantity) {
            try {
                txLabMapper.insertOrder(userId, productId, quantity);
                deductStock(productId, quantity);
            } catch (RuntimeException e) {
                log.error("下单失败", e);
            }
        }
    
        // 坏写法四:库存不足时抛受检异常
        @Transactional
        public void placeOrderChecked(Long userId, Long productId, int quantity) throws StockException {
            txLabMapper.insertOrder(userId, productId, quantity);
            if (txLabMapper.deductStock(productId, quantity) == 0) {
                throw new StockException("库存不足");
            }
        }
    
        // 最后一步用:protected 方法上的事务
        @Transactional
        protected void placeOrderProtected(Long userId, Long productId, int quantity) {
            txLabMapper.insertOrder(userId, productId, quantity);
            deductStock(productId, quantity);
        }
    }

    IDEA 可能会把 doPlace 上的 @Transactional 标出来,先别管它,这正是要复现的问题。

  5. 写一个 Controller,按地址里的名字调对应的方法。它在调之前、调之后各数一次 orders 有几行,把多出的行数和抛出的异常一起返回:

    java
    // src/main/java/com/shop/txlab/TxLabController.java
    package com.shop.txlab;
    
    import org.springframework.web.bind.annotation.PathVariable;
    import org.springframework.web.bind.annotation.PostMapping;
    import org.springframework.web.bind.annotation.RestController;
    
    @RestController
    public class TxLabController {
    
        private final TxLabService txLabService;
        private final TxLabMapper txLabMapper;
    
        public TxLabController(TxLabService txLabService, TxLabMapper txLabMapper) {
            this.txLabService = txLabService;
            this.txLabMapper = txLabMapper;
        }
    
        // 每次都是用户 1 买商品 7 买 999 件,库存一定不够
        @PostMapping("/tx-lab/{name}")
        public String run(@PathVariable("name") String name) {
            long before = txLabMapper.countOrders();
            String error = "没有";
            try {
                switch (name) {
                    case "self-call" -> txLabService.placeOrderSelfCall(1L, 7L, 999);
                    case "private" -> txLabService.placeOrderPrivate(1L, 7L, 999);
                    case "swallow" -> txLabService.placeOrderSwallow(1L, 7L, 999);
                    case "checked" -> txLabService.placeOrderChecked(1L, 7L, 999);
                    case "protected" -> txLabService.placeOrderProtected(1L, 7L, 999);
                    default -> throw new IllegalArgumentException("没有这个场景");
                }
            } catch (Exception e) {
                error = e.getClass().getSimpleName() + " " + e.getMessage();
            }
            long added = txLabMapper.countOrders() - before;
            return "异常:" + error + ";orders 多了 " + added + " 行\n";
        }
    }

    TxLabController 和 TxLabService 在同一个包里,所以它调得到 protected 的 placeOrderProtected。

  6. 启动:

    bash
    ./mvnw spring-boot:run

    看到 Started ShopApplication 以后,在第二个终端里把四种坏写法各打一次:

    bash
    curl -X POST localhost:8080/tx-lab/self-call
    curl -X POST localhost:8080/tx-lab/private
    curl -X POST localhost:8080/tx-lab/swallow
    curl -X POST localhost:8080/tx-lab/checked
    text
    异常:IllegalStateException 库存不足;orders 多了 1 行
    异常:IllegalStateException 库存不足;orders 多了 1 行
    异常:没有;orders 多了 1 行
    异常:StockException 库存不足;orders 多了 1 行

    四次都多了一行:订单插进去了,库存没扣。第三次连异常都没有,调用方以为下单成功了。再看第一个终端的日志:打前两个时,日志里一行事务的日志都没有,说明根本没开事务;打后两个时,各有一行 Creating new transaction with name [com.shop.txlab.TxLabService.placeOrderSwallow](第四次是 placeOrderChecked),后面跟着的是 Committing,不是 Rolling back:事务开了,却提交了。

  7. 一个个修。先自己想怎么改,改完重启,再打一次,直到返回的是 orders 多了 0 行。四个方法可以一起改完再重启。

    第一种,placeOrderSelfCall:提示,注解该贴在哪个方法上?

    答案

    把 @Transactional 贴在入口 placeOrderSelfCall 上,事务在入口就开好了,里面的 deductStock 虽然还是自调用,SQL 也在这个事务里:

    java
    @Transactional
    public void placeOrderSelfCall(Long userId, Long productId, int quantity) {
        txLabMapper.insertOrder(userId, productId, quantity);
        deductStock(productId, quantity);
    }

    第二种,placeOrderPrivate:提示,代理看得见哪个方法?

    答案

    把注解从 private 的 doPlace 挪到 public 的 placeOrderPrivate 上。doPlace 上那个可以删掉,它在 private 方法上从来不生效:

    java
    @Transactional
    public void placeOrderPrivate(Long userId, Long productId, int quantity) {
        doPlace(userId, productId, quantity);
    }
    
    private void doPlace(Long userId, Long productId, int quantity) {
        txLabMapper.insertOrder(userId, productId, quantity);
        deductStock(productId, quantity);
    }

    第三种,placeOrderSwallow:提示,代理要看到什么才会回滚?

    答案

    记完日志把异常接着抛出去:

    java
    } catch (RuntimeException e) {
        log.error("下单失败", e);
        throw e;
    }

    改完以后,这个接口返回的就不是「异常:没有」了,而是 IllegalStateException 库存不足:下单失败了,调用方应该知道。不想往外抛的,可以在 catch 里调 TransactionAspectSupport.currentTransactionStatus().setRollbackOnly()(import org.springframework.transaction.interceptor.TransactionAspectSupport),返回的还是「异常:没有」,但 orders 也不多一行。

    第四种,placeOrderChecked:提示,受检异常要怎样才回滚?

    答案

    在注解上写明受检异常也回滚:

    java
    @Transactional(rollbackFor = Exception.class)
    public void placeOrderChecked(Long userId, Long productId, int quantity) throws StockException {

    另一个办法是让 StockException 继承 RuntimeException,那样它就成了运行时异常,方法签名上的 throws 也可以删掉。

    四个都改好、重启以后,再打一遍:

    text
    异常:IllegalStateException 库存不足;orders 多了 0 行
    异常:IllegalStateException 库存不足;orders 多了 0 行
    异常:IllegalStateException 库存不足;orders 多了 0 行
    异常:StockException 库存不足;orders 多了 0 行

    第三行用的是 setRollbackOnly() 那种改法的,是 异常:没有;orders 多了 0 行。日志里这次每个都有 Creating new transaction,后面跟着的是 Rolling back JDBC transaction。

  8. 最后验证旧说法。网上和 AI 常说「@Transactional 只对 public 方法生效」,placeOrderProtected 是 protected 的,从另一个 Bean(这里是 TxLabController)调它。先想一想:会多一行,还是不多?想好了再打:

    bash
    curl -X POST localhost:8080/tx-lab/protected
    答案
    text
    异常:IllegalStateException 库存不足;orders 多了 0 行

    事务生效了,日志里有 Creating new transaction with name [com.shop.txlab.TxLabService.placeOrderProtected] 和 Rolling back。「只对 public 生效」是 Spring 5(Spring Boot 2)的规则,Spring 6(Spring Boot 3)起,用 Spring Boot 默认的 CGLIB 代理时,protected 和包级方法上的注解也生效,只有 private 和 final 方法不行,见事务为什么没生效的版本提醒。

    你看到的要是 orders 多了 1 行,日志里也没有这个方法的 Creating new transaction,先看 pom.xml 里 parent 的版本是不是 4 开头;再看 application.yml 里有没有把 spring.aop.proxy-target-class 设成 false,用 JDK 动态代理时确实只有 public 方法生效。

    final 方法不放进这一页:给 placeOrderSelfCall 加上 final,它会在代理对象身上执行,txLabMapper 是 null,第一行就空指针,一条 SQL 都没执行,用「orders 多没多一行」看不出事务的问题。想看的话可以自己加上 final 试一次,返回的是 NullPointerException,看完删掉。

做完了

第 6 步四次都是 orders 多了 1 行,第 7 步改完以后四次都是 orders 多了 0 行,第 8 步 protected 方法也是 0 行,就做对了。

前面几次多出来的订单还留在表里。到 hello-backend 目录里再执行一遍 lab.sql,库 shop 就回到最初的样子:

bash
docker compose exec -T mysql mysql -uroot -psecret --default-character-set=utf8mb4 < lab.sql

不用了,在第一个终端按 Ctrl + C 停掉项目,再 docker compose stop 停掉 MySQL。com.shop.txlab 整个包只是这一页用的,删掉也行;application.yml 里的 logging 那几行嫌日志多也可以删掉。

做不出来时

  • 加了 logging 那几行,日志里却一行事务的日志都没有,连修好以后也没有:你的项目用的事务管理器可能不是这个类,把 org.springframework.jdbc.support.JdbcTransactionManager 换成 org.springframework.jdbc,范围大一些。
  • 启动失败,报告里说找不到 com.shop.txlab.TxLabMapper 类型的 Bean:看 TxLabMapper 上有没有 @Mapper,第一行是不是 package com.shop.txlab;,文件是不是在 src/main/java/com/shop/txlab 下面。
  • curl 返回 404:地址是 /tx-lab/…,方法要用 -X POST;再看是不是忘了重启。
  • 第 6 步返回的是 orders 多了 0 行:先确认第 1 步执行过 lab.sql、商品 7 的库存不到 999;再看 TxLabService 是不是照抄的,坏写法里有没有多贴了 @Transactional。
  • 返回 异常:DataIntegrityViolationException … 或别的数据库错误:多半是 orders 表的结构和数据库那一块建的不一样,重新执行一遍 lab.sql。