mybatisplus手动获取数据源执行非主数据库事务
class A {
@Resource
private DataSourceTransactionManager dataSourceTransactionManager;
@Autowired
private DataSource dataSource;
public void add(MDTO dto) throws AppException {
final DataSource testdb = ((DynamicRoutingDataSource) dataSource).getDataSource("testdb");
dataSourceTransactionManager.setDataSource(testdb);
DefaultTransactionDefinition transactionDefinition = new DefaultTransactionDefinition();
transactionDefinition.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
final TransactionStatus transactionStatus = dataSourceTransactionManager.getTransaction(transactionDefinition);
try {
Map<String, Object> result = new HashMap<>();
result.put("test1", 0);
result.put("test2", 0);
baseMapper.WAdd(result);
dataSourceTransactionManager.commit(transactionStatus);
} catch (Exception e) {
if (dataSourceTransactionManager != null) {
dataSourceTransactionManager.rollback(transactionStatus);
}
e.printStackTrace();
throw e;
}
}
}