Youzi - @Transactional
type: channel
link: https://www.autisn.com/index.php/tag/Transactional/
items: 在AOP配置事务控制或注解 @Transactional控制事务中，try…catch…使事务失效的解决办法

在AOP配置事务控制或注解 @Transactional控制事务中，try…catch…使事务失效的解决办法
type: item
date: 2022-09-29T10:10:23+08:00
description: 可在catch中抛出运行时异常throw new RuntimeException(e)（注：默认回滚的是RuntimeException，如果你想触发其他异常的回滚，需要在注解上配置一下）手动回滚TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(),使得事务生效，出现异常回滚。@Transactional(rollbackFor = Exception.class) public AjaxResult update(@RequestBody RestaurantVo entity) { AjaxResult ajaxResult = new AjaxResult(); try { service.save(entity); return ajaxResult.success("success"); } catch (Exception e) { //throw new RuntimeException(e); TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); return ajaxResult.fail("500", e.getMessage()); } }