配置
第一个数据源的配置
@Configuration
@MapperScan(basePackages = "com.nit310.store.mapper.ds1", sqlSessionFactoryRef = "ds1SqlSessionFactory")
public class DataSourceConfig1 {
// 将这个对象放入Spring容器中
@Bean(name = "ds1DataSource")
// 表示这个数据源是默认数据源
@Primary
// 读取application.properties中的配置参数映射成为一个对象
// prefix表示参数的前缀
@ConfigurationProperties(prefix = "spring.datasource.ds1")
public DataSource getDateSource1()
{
return DataSourceBuilder.create().build();
}
@Bean(name = "ds1SqlSessionFactory")
// 表示这个数据源是默认数据源
@Primary
// @Qualifier表示查找Spring容器中名字为test1DataSource的对象
public SqlSessionFactory test1SqlSessionFactory(@Qualifier("ds1DataSource") DataSource datasource)
throws Exception
{
SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
bean.setDataSource(datasource);
bean.setMapperLocations(
// 设置mybatis的xml所在位置
new PathMatchingResourcePatternResolver().getResources("classpath*:mapper/ds1/*.xml"));
bean.setTypeAliasesPackage("com.nit310.store.entity");
bean.getObject().getConfiguration().setMapUnderscoreToCamelCase(true);
return bean.getObject();
}
@Bean("ds1SqlSessionTemplate")
// 表示这个数据源是默认数据源
@Primary
public SqlSessionTemplate test1SqlSessionTemplate(
@Qualifier("ds1SqlSessionFactory") SqlSessionFactory sessionFactory)
{
return new SqlSessionTemplate(sessionFactory);
}
// 事务配置
@Bean(name = "ds1DataSourceTransactionManager")
public DataSourceTransactionManager transactionManager(@Qualifier("ds1DataSource") DataSource dataSource){
return new DataSourceTransactionManager(dataSource);
}
}
第二个数据源的配置
@Configuration
@MapperScan(basePackages = "com.nit310.store.mapper.ds2", sqlSessionFactoryRef = "ds2SqlSessionFactory")
public class DataSourceConfig2 {
@Bean(name = "ds2DataSource")
@ConfigurationProperties(prefix = "spring.datasource.ds2")
public DataSource getDateSource2()
{
return DataSourceBuilder.create().build();
}
@Bean(name = "ds2SqlSessionFactory")
public SqlSessionFactory test2SqlSessionFactory(@Qualifier("ds2DataSource") DataSource datasource)
throws Exception
{
SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
bean.setDataSource(datasource);
bean.setMapperLocations(
new PathMatchingResourcePatternResolver().getResources("classpath*:mapper/ds2/*.xml"));
bean.setTypeAliasesPackage("com.nit310.store.entity");
bean.getObject().getConfiguration().setMapUnderscoreToCamelCase(true);
return bean.getObject();
}
@Bean("ds2SqlSessionTemplate")
public SqlSessionTemplate test2SqlSessionTemplate(
@Qualifier("ds2SqlSessionFactory") SqlSessionFactory sessionFactory)
{
return new SqlSessionTemplate(sessionFactory);
}
@Bean(name = "ds2DataSourceTransactionManager")
public DataSourceTransactionManager transactionManager(@Qualifier("ds2DataSource") DataSource dataSource){
return new DataSourceTransactionManager(dataSource);
}
}
具体使用
在需要开启事务的接口或实现类中添加注解,并指定Manager
@Transactional(rollbackFor = Exception.class, transactionManager = "ds2DataSourceTransactionManager")
Long addToOrderMaster(OrderMaster master, OrderDetail[] details);