解决参考: https://blog.youkuaiyun.com/Mr_Smile2014/article/details/49455483

异常信息
ERROR c.r.f.w.e.DefaultExceptionHandler - [notFount,50] - 运行时异常:
org.springframework.transaction.UnexpectedRollbackException: Transaction rolled back because it has been marked as rollback-only
直接上代码:
controller
@PostMapping("/testFunction")
@ResponseBody
// @Transactional //注意这里啊,service层有异常处理了,controller还是删掉这个没必要的吧
public AjaxResult testFunction()
{
try {
testService.testServiceFunction();
} catch (Exception e) {
//这里捕捉testServiceFunction方法扔出来的异常并处理,解决异常:Transaction rolled back because it has been marked as rollback-only
return AjaxResult.error("执行出错,数据回滚");
}
return toAjax(1);
}
service 及 serviceImpl
public int testServiceFunction() throws Exception;
@Override
@Transactional
public int testServiceFunction() throws Exception{
try {
//操作1
//操作2
//操作3
//这里代码异常了,用try捕捉,catch抛出异常到上一层
}catch (Exception e){
System.out.println(e);
System.out.println("---数据执行异常,Transactional事务回滚数据。controller捕捉异常,并做相关提示--");
throw e;
}
return 0;
}
我这里是单一的service方法里用到 Transactional ,并不是像网上其他人那样多个service方法相互调用导致的异常;
之前为了测试,直接在controller层方法上使用了Transactional注解,导致我的service层方法抛出异常后,即使controller方法里捕捉处理了异常,还是会一直报 ... rollback-only ... ,删掉controller层方法上的Transactional注解,就好了。。

本文详细解析了在Spring框架中遇到的UnexpectedRollbackException异常,即事务被标记为回滚-only的问题。通过分析Controller与Service层的Transactional注解使用,提供了解决方案,避免了异常处理不当导致的持续回滚。
9853

被折叠的 条评论
为什么被折叠?



