系列四十二、Spring的事务传播行为案例演示(二)#REQUIRED

一、演示Spring的默认传播行为(REQUIRED)

1.1、运行之前表中的数据

1.2、StockServiceImpl

/**
 * @Author : 一叶浮萍归大海
 * @Date: 2023/10/30 15:43
 * @Description:
 */
@Service(value = "stockServiceREQUIRED")
public class StockServiceImpl extends ServiceImpl implements StockService {

    @Resource
    private StockMapper stockMapper;

    @Resource
    private IntegralService integralService;

    @Transactional(propagation = Propagation.REQUIRED,rollbackFor = Exception.class)
    @Override
    public void reduceStock(Long id, Integer num) {
        try {
            // 减库存
            StockDO dbStock = stockMapper.selectById(id);
            StockDO updateStock = new StockDO();
            BeanUtils.copyProperties(dbStock, updateStock);
            updateStock.setNum(dbStock.getNum() - num);
            stockMapper.updateById(updateStock);

            // 增加积分
            IntegralDO updateIntegral = new IntegralDO();
            updateIntegral.setPreIntegral(0);
            updateIntegral.setCurrentIntegral(1000);
            updateIntegral.setUserId(1L);
            integralService.addIntegral(updateIntegral);

            // 模拟异常
            int i = 10 / 0;
        } catch (BeansException e) {
            throw new RuntimeException(e);
        }
    }
}

1.3、IntegralServiceImpl

/**
 * @Author : 一叶浮萍归大海
 * @Date: 2023/10/30 15:42
 * @Description:
 */
@Service(value = "integralServiceREQUIRED")
public class IntegralServiceImpl extends ServiceImpl implements IntegralService {

    @Resource
    private IntegralMapper integralMapper;

    @Transactional(propagation = Propagation.REQUIRED,rollbackFor = Exception.class)
    @Override
    public void addIntegral(IntegralDO updateIntegral) {
        integralMapper.insert(updateIntegral);
    }
}

1.4、测试结果

系列四十二、Spring的事务传播行为案例演示(二)#REQUIRED_第1张图片

1.5、数据变化 

stock表中的库存数量没有发生变化,integral(积分表)表没有增加积分。符合预期

你可能感兴趣的:(Spring全家桶面试系列,数据库,mysql)