参考文章:
https://blog.csdn.net/fubaojiexing/article/details/79057639
https://blog.csdn.net/Dongguabai/article/details/80788585
https://www.jianshu.com/p/00758c77bf60
https://note.youdao.com/ynoteshare1/index.html?id=4eab4c614ec0825fdcf6f6251f47161e&type=note
https://blog.csdn.net/u010963948/article/details/79208328
主要的失效原因有以下几种:
1.spring会对unchecked异常进行事务回滚;如果是checked异常则不回滚。
java里面将派生于Error或者RuntimeException(比如空指针,1/0)的异常称为unchecked异常,
其他继承自java.lang.Exception得异常统称为Checked Exception,如IOException、TimeoutException等
你的异常类型是不是unchecked异常。
如果check异常也想回滚怎么办,注解上面写明异常类型即可。
@Transactional(rollbackFor=Exception.class)
2. @Transactional 注解标注的方法不是public类型的。
3. 代理类的原因。
我想在controller层调用两个service 事务方法,失败。
由于我用的dubbo 微服务,controller层和service层是两个独立的服务。controller层未配置数据源, 事务不起作用的原因未找到,可能跟数据未配置有关系,工作时间紧,做个笔记以后有机会再查。。。。
service层事务处理正常,代码如下:
```java
/**
* 添加快递单 返回记录id
* rollbackFor = Exception.class 抛出 Exception 时回滚事物,不需要手动回滚
*
* @param snWaybillInfoEntity
* @return
* @throws PSBCommonException
*/
@Override
@Transactional(readOnly = false, propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
public int insterWaybillSubscribeInfo(SNWaybillInfoEntity snWaybillInfoEntity, List<TemInfoitem> temInfoitems) throws PSBCommonException {
log.info("====== 添加快递单,入参:" + JSON.toJSONString(snWaybillInfoEntity));
Integer result = 0;
try {
result = waybillSubscribeDao.insterWaybillSubscribeInfo(snWaybillInfoEntity);
if (result == 0) {
throw new PSBCommonException(RestErrorCodeConstants.STATUS_SYSTEM_ERROR, RestErrorCodeConstants.STATUS_SYSTEM_ERROR_INFO + ",插入快递单失败!");
}
if (null != temInfoitems && temInfoitems.size() > 0) {
//设置快递单ID
for (TemInfoitem temInfoitem : temInfoitems) {
temInfoitem.setWaybillId(snWaybillInfoEntity.getId());
}
result = waybillSubscribeDao.insterWaybillTemInfoitems(temInfoitems);
if (result == 0) {
throw new PSBCommonException(RestErrorCodeConstants.STATUS_SYSTEM_ERROR, RestErrorCodeConstants.STATUS_SYSTEM_ERROR_INFO + ",插入商品信息失败!");
}
throw new SQLException();
}
} catch (SQLException e) {
// 抛出异常回滚事物,不需要手动回滚
// TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
log.info("====== 添加快递单失败!");
log.error(e);
throw new PSBCommonException(RestErrorCodeConstants.SQL_ERROR_CODE, RestErrorCodeConstants.SQL_ERROR_INFO);
}
log.info("====== 添加快递单,出参,添加记录id:" + snWaybillInfoEntity.getId());
return snWaybillInfoEntity.getId();
}