当前位置: 代码迷 >> 综合 >> Spring Boot定时任务quartz发生异常时数据库的回滚
  详细解决方案

Spring Boot定时任务quartz发生异常时数据库的回滚

热度:43   发布时间:2024-02-06 21:47:49.0

无法回滚的代码

如下伪代码,在两条数据库插入操作之间抛出了异常,本来以为添加了@Transactional(rollbackFor = Exception.class)注解发生异常后会回滚,但是事与愿违,结果是发生异常后没回滚,第一条数据插入成功了

@Service
@Transactional(rollbackFor = Exception.class)
public class TestJobBean extends QuartzJobBean {@Overrideprotected void executeInternal(JobExecutionContext jobExecutionContext) {dbService.insert("野猿新一");int i = Integer.parseInt("我不是int啦"); // 此处会抛出NumberFormatException异常dbService.insert("野猿新二");}
}

可以回滚的代码

将业务相关的数据库操作代码抽出到独立的Service中,然后在该Service上添加@Transactional(rollbackFor = Exception.class)注解,如下代码所示

@Service
@Transactional(rollbackFor = Exception.class)
public class DBService {protected void doSomething() {dbService.insert("野猿新一");int i = Integer.parseInt("我不是int啦"); // 此处会抛出NumberFormatException异常dbService.insert("野猿新二");}
}
@Service
public class TestJobBean extends QuartzJobBean {@ResourceDBService dbService;@Overrideprotected void executeInternal(JobExecutionContext jobExecutionContext) {dbService.doSomething();}
}

这样就OK了,发生异常后就可以成功,至于为啥要这样写我也不清楚,有清楚的老铁可以留言评论下

  相关解决方案