rollback-only事务

前言

事务注解在进行时,抛出了异常

示例

UserService类上

less 复制代码
@Slf4j
@Service
public class UserService {

    @Autowired
    private UserRepository userRepository;


    @Transactional(rollbackFor = Exception.class)
    public void say() {
        log.info("============执行say()==============");
        User user = new User();
        user.setUserName("aaa");
        userRepository.save(user);
        int a = 1 / 0;
    }

}
less 复制代码
@Slf4j
@Service
public class PersonService {

    @Autowired
    private UserService userService;

    @Transactional(rollbackFor = Exception.class)
    public void say() {
        log.info("PersonService say");
        try {
            userService.say();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

准备一个接口

less 复制代码
@Slf4j
@RestController
public class IndexController {


    @Autowired
    private PersonService personService;

    @GetMapping("/hello")
    public Integer hello() {
        personService.say();
        return 1;
    }
}

访问

bash 复制代码
http://ip:端口/hello

发现会抛事务异常,

原因是A方法又catch到B方法抛出的异常,但是A方法catch到异常后没有继续往上抛出,而是继续执行后面的代码,最后正常提交事务,那么就会抛出 Transaction rolled back because it has been marked as rollback-only这异常!(因为AB是用同一个事务,在B方法执行的时候这个事务就标记为rollback-only,然后A方法继续使用该事务,然后又执行事务提交的操作,所以最后会抛异常)

相关推荐
独泪了无痕7 小时前
MyBatis魔法堂:结果集映射
后端·mybatis
copyer_xyf7 小时前
LangChain 调用 LLM
后端·python·agent
copyer_xyf7 小时前
Prompt 组织管理
后端·python·agent
摇滚侠9 小时前
SpringMVC 入门到实战 文件上传 75-77
java·后端·spring·maven·intellij-idea
fox_lht11 小时前
15.3.改进我们之前的输入、输出项目
开发语言·后端·学习·rust
大鸡腿同学11 小时前
用 AI 肝了一个星期的智能客服助手,看看怎么个事
后端
IT_陈寒11 小时前
Python的os.path.join居然能这么坑?
前端·人工智能·后端
张忠琳11 小时前
【Go 1.26.4】Golang Channel 深度解析
开发语言·后端·golang
Rain50912 小时前
2.1 Nest.js 项目初始化与模块化架构
开发语言·前端·javascript·后端·架构·数据分析·node.js