controller异常手动回滚事物

我们都知道,@Transactional要放在service层,并且只需要放到最外层的方法上就可以了。

controller层使用@Transactional注解是无效的。但是可以在controller层方法的catch语句中增加:TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();语句,手动回滚,这样上层就无需去处理异常  

@RequestMapping(value = "/delrecord", method = {RequestMethod.GET})
@Transactional(rollbackFor = Exception.class)
public String delRecord(HttpServletRequest request) {
try {
//省略业务代码……
} catch (Exception e) {
log.error("操作异常",e);
TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();//contoller中增加事务
return failure("操作失败!");
}
}
原文地址:https://www.cnblogs.com/Hello-TomCat/p/14031531.html