JAVA@Transactional常用失效场景
@Transactional(rollbackFor = {RuntimeException.class, Error.class}) @Override public boolean create() { create1(); create2(); return true; }
public void create1() {
Student student = new Student();
student.setName("事务1");
//不能为空
student.setGender(1);
int result = studentMapper.insert(student);
if (result != 1) {
throw new RuntimeException("新增失败");
}
}
public void create2() {
Student student = new Student();
student.setName("事务2");
student.setGender(1);
studentMapper.insert(student);
Student student2 = new Student();
student2.setName("事务3");
int result = studentMapper.insert(student2);
if (result != 1) {
throw new RuntimeException("新增失败");
}
}
以上事务生效。在create()方法上添加事务,create2()因为gender为空产生报错,促使整个create()方法回滚,整体可以理解为是长事务;
@Override
public boolean create() {
create1();
create2();
return true;
}
@Transactional(rollbackFor = {RuntimeException.class, Error.class})
public void create1() {
Student student = new Student();
student.setName("事务1");
//不能为空
student.setGender(1);
int result = studentMapper.insert(student);
if (result != 1) {
throw new RuntimeException("新增失败");
}
}
@Transactional(rollbackFor = {RuntimeException.class, Error.class})
public void create2() {
Student student = new Student();
student.setName("事务2");
student.setGender(1);
studentMapper.insert(student);
Student student2 = new Student();
student2.setName("事务3");
int result = studentMapper.insert(student2);
if (result != 1) {
throw new RuntimeException("新增失败");
}
}
以上事务触发不生效规则——同一个类中里层方法(create1(),create2())添加@Transactional注解不生效,需要在外层方法(create())添加@Transactional注解才会生效。以上两个方法create1和create2均加有 @Transactional注解,但是这种方式不会生效,create1会执行成功并提交到数据库,create2的事务2会成功插入数据库,但是事务3不会插入数据库,从而引发了数据的不一致性。
@Override public boolean create() { studentService2.create1(); studentService2.create2(); return true; }
StudentService:
@Transactional(rollbackFor = {RuntimeException.class, Error.class}) public void create1() { Student student = new Student(); student.setName("事务1"); //不能为空 student.setGender(1); int result = studentMapper.insert(student); if (result != 1) { throw new RuntimeException("新增失败"); } } @Transactional(rollbackFor = {RuntimeException.class, Error.class}) public void create2() { Student student = new Student(); student.setName("事务2"); student.setGender(1); studentMapper.insert(student); Student student2 = new Student(); student2.setName("事务3"); int result = studentMapper.insert(student2); if (result != 1) { throw new RuntimeException("新增失败"); } }
此种方式事务生效,事务1能够成功保存到数据库,事务2和事务3因为异常无法保存到数据库。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 【自荐】一款简洁、开源的在线白板工具 Drawnix