SpringBoot使用多数据源时,事物控制
码云地址
https://gitee.com/imbobo_bo/angel-bo
代码
@Bean public SqlSessionFactory sqlSessionFactoryBean(DynamicDataSource dynamicDataSource) throws Exception { SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean(); sqlSessionFactoryBean.setDataSource(dynamicDataSource); PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(); sqlSessionFactoryBean.setMapperLocations(resolver.getResources("classpath:/mapper/*.xml")); sqlSessionFactoryBean.setTypeAliasesPackage("com.angel.bo.beans.admin.entity"); return sqlSessionFactoryBean.getObject(); }
DynamicDataSource 这个为动态数据源配置
/** * 使用DatabaseContextHolder获取当前线程的DatabaseType */public class DynamicDataSource extends AbstractRoutingDataSource { @Override protected Object determineCurrentLookupKey() { return DataSourceContextHolder.getDataSourceType(); }}
开启springBoot事物管理
@EnableTransactionManagement
servic类上加上事物注解
@Service@Transactional(rollbackFor = Exception.class)
现象
在上面代码,执行方法时,事物失效,不回滚
解决
缺少针对动态数据源的事物控制
@Bean public DataSourceTransactionManager transactionManager(DynamicDataSource dynamicDataSource) { return new DataSourceTransactionManager(dynamicDataSource); }