版权声明:分享知识是一种快乐,愿你我都能共同成长! https://blog.csdn.net/qidasheng2012/article/details/84786143
一、问题:在service层写下面代码,事务不会回滚
public void save(User user, Card card){
try {
userDao.save(user);
CardDao.save(card);
} catch (Exception e) {
logger.info("异常信息:"+e);
}
}
二、原因分析
spring 的默认事务机制:当出现unchecked异常时候回滚,checked异常的时候不会回滚;
- unchecked异常:error和runtime异常
- checked异常:需要try catch或向上抛出的异常,例如IOException
因为上面代码进行try catch,所以不会回滚
三、解决办法
方式一、service层不做try catch处理,直接向上抛异常,由controller层进行统一处理(推荐)
方式二、在catch中抛出RuntimeException
public void save(User user, Card card)throws RuntimeException {
try {
userDao.save(user);
CardDao.save(card);
} catch (Exception e) {
logger.info("异常信息:"+e);
throw new RuntimeException();
}
}
方式三、在catch中手动回滚
public void save(User user, Card card){
try {
userDao.save(user);
CardDao.save(card);
} catch (Exception e) {
logger.info("异常信息:"+e);
TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
}
}
四、扩展
配置设置所有异常回滚
@Transactional(rollbackFor = { Exception.class })