定义事务管理器DataSourceTransactionManager
@Bean(name = "orderTransactionManager")
public DataSourceTransactionManager orderTransactionManager() {
return new DataSourceTransactionManager(getOrderDataSource());
}
注入事务管理器然后开启
@Resource(name = "masterTransactionManager")
private DataSourceTransactionManager dataSourceTransactionManager;
private void insertCommentRefuseMessage(CommentRejectDto dto) {
//手动开启事务和回滚
// 1.获取事务定义
DefaultTransactionDefinition def = new DefaultTransactionDefinition();
// 2.设置事务隔离级别,开启新事务
def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
// 3.获得事务状态
TransactionStatus status = dataSourceTransactionManager.getTransaction(def);
if (CollectionUtil.isNotEmpty(dto.getIds())) {
int i=0;
for (Long id : dto.getIds()) {
try {
OmsComment omsComment = omsCommentMapper.selectByPrimaryKey(id);
umsMemberMessage.setProductCommentId(id);
umsMemberMessage.setToMemberId(omsComment.getMemberId());
umsMemberMessageMapper.insertSelective(umsMemberMessage);
if (i==2){
throw new Exception();
}
i++;
} catch (Exception throwable) {
//masterTransactionManager 数据源回滚
dataSourceTransactionManager.rollback(status);
throw new ApiException("添加消息失败!");
}
}
}
}