@Transactional
🏷️ Spring Boot
@Transactional
在默认配置下,只会在发生 RuntimeException
时才会触发回滚操作。
如要在发生自定义的异常时回滚,需要通过 rollbackFor 字段指定自定义异常的类型。示例如下:
java
@Slf4j
@RestController
@RequestMapping("test")
@RequiredArgsConstructor
public class TestController {
private final ILogService logService;
@GetMapping("rollback")
@Transactional(rollbackFor = MyException.class)
public void test() throws Exception {
logService.createLog(new Log() {{
setKey(RandomStringUtils.getRandomString(6));
setUserId(1);
}});
throw new MyException("测试异常");
}
}