TransactionTemplate编程式事务用法测试

TransactionTemplate用法测试

TransactionTemplate 编程式事务,相比于注解事务,能够更细粒度的控制事务

  1. execute里如果不加try catch ,异常后可以回滚,但是会向外抛出异常,不会走后续代码
public void testTransaction() {
    Article article = new Article();
    article.setTitle("正经‘’‘’。。。");
    article.setImageInput("20220112/ddd.jpg");
    article.setContent("张三你 洒洒水啊撒");

    Category category = new Category();
    category.setName("我的测试");
    boolean flag = transactionTemplate.execute(status -> {
        
            categoryMapper.insertSelective(category);
            int a = 1/0;
            article.setCid(category.getId()+"");
            articleMapper.insertSelective(article);
            return Boolean.TRUE;
    });
    System.out.println("执行结果返回数据:"+flag);
}
  1. 加上try catch后,必须在catch中手动加上status.setRollbackOnly(),否则无法回滚数据
        boolean flag = transactionTemplate.execute(status -> {
            try {
                categoryMapper.insertSelective(category);
                int a = 1/0;
                article.setCid(category.getId()+"");
                articleMapper.insertSelective(article);
                return Boolean.TRUE;
            } catch (Exception e) {
                status.setRollbackOnly();
                return Boolean.FALSE;
            }
        });
  1. 如果execute 内部调用其他serviceA方法,这个serviceA使用@Transactional(rollbackFor = Exception.class)标注的事务
    • 如果serviceA异常回滚,全部都回滚
    • 如果execute里异常,全部回滚
        boolean flag = transactionTemplate.execute(status -> {
            try {
                categoryMapper.insertSelective(category);
                categoryService.insert(category);
                int a = 1/0;
                article.setCid(category.getId()+"");
                articleMapper.insertSelective(article);
                return Boolean.TRUE;
            } catch (Exception e) {
                status.setRollbackOnly();
                return Boolean.FALSE;
            }
        });

你可能感兴趣的:(TransactionTemplate编程式事务用法测试)