栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Spring的@Transactional失效的几种场景

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Spring的@Transactional失效的几种场景

相信大家在日常工作中也都曾遇到过@Transactional注解失效的情况,今天我来总结下@Transactional注解失效的6中情况。 1.方法是非public修饰的

解决方法: 改成public修饰。

2.异常被捕获了,没有抛出

解决方法: 直接抛出需要回滚的异常,不要try-catch住。

3.方法内部直接调用 代码示例:
@Service
public class TestService {

    @Autowired
    TestMapper testMapper;

    public void testA() {
        testMapper.testInsert("INSERT INTO `tb_my_test` (`code_id`, `is_show`) VALUES ('1', 1);");
        testB();
    }

    @Transactional(rollbackFor = {BusinessException.class})
    public void testB(){
        testMapper.testInsert("INSERT INTO `tb_my_test` (`code_id`, `is_show`) VALUES ('2', 2);");
        throw new BusinessException("异常");
    }


}

以上情况即使抛出异常也无法回滚

解决方法:

@Service
public class TestService {

    @Autowired
    TestMapper testMapper;

    
    @Autowired
    TestService testService;

    public void testA() {
        testMapper.testInsert("INSERT INTO `tb_my_test` (`code_id`, `is_show`) VALUES ('1', 1);");
        // 在内部调用的时候 用testService调用testB()方法 可以实现对testB()回滚
        testService.testB();
    }

    @Transactional(rollbackFor = {BusinessException.class})
    public void testB(){
        testMapper.testInsert("INSERT INTO `tb_my_test` (`code_id`, `is_show`) VALUES ('2', 2);");
        throw new BusinessException("异常");
    }


}

注意以上示例只能回滚testB() 无法回滚testA()。

4.新开启一个线程

解决方法: 在添加了@Transactional注解的方法中,不要新启一个线程执行插入、更新、删除操作。

5.数据库本身不支持 6.事务传播属性设置错误

如果设置以非事务方式运行的传播属性,无法开启事务。

解决方法: 设置适合自己的实际情况的传播属性。

以上就是@Transactional失效的几种场景总结,希望能帮到大家!

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/846015.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号