SpringBoot+MybatisPlus多数据源添加事务,数据源切换失效问题
【问题描述】
上篇文章说到了怎么用spring boot去整合MP的多数据源插件,在使用中,用到了加上了spring的事务注解(@Transactional),发现@DS切换数据源会失效。在网上看了很多解决办法,都觉得很繁琐,由于我用的是MP的多数据源,所以可以直接使用MP提供的事务注解: @DSTransactional
案例:
代码写的比较烂,这边只是为了快速实现功能
@Service
public class AlarmServiceImpl extends ServiceImpl<AlarmMapper, Alarm> implements IAlarmService {
@Autowired
IUserIntegralService userIntegralService;
@Autowired
private ISysUserService sysUserService;
// MP的事务注解
@DSTransactional
public Integer selectCount(Alarm alarm){
one(alarm.getDeviceId());
two(alarm.getGroupName());
return 1;
}
//用的数据库
public Boolean one(String email) {
return sysUserService.update(email);
}
public Boolean two(String big) {
//模拟代码出错事务回滚
//int i = 1/0;
return userIntegralService.update(big);
}
}
【最后】
事务可以回滚,也可以切换数据源