版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
配置文件配置多个数据源
# 数据源1
spring.datasource.data.driverClassName=com.mysql.jdbc.Driver
spring.datasource.data.url=jdbc:mysql://IP地址:3306/数据库?useUnicode=true&characterEncoding=utf8
spring.datasource.data.username=root
spring.datasource.data.password=密码
#数据源1
spring.datasource.recod.driverClassName=com.mysql.jdbc.Driver
spring.datasource.recod.url=jdbc:mysql://IP地址:3306/数据库?useUnicode=true&characterEncoding=utf8
spring.datasource.recod.username=root
spring.datasource.recod.password=密码
编写config类
basePackages 接口所在包路径
@ConfigurationProperties(prefix = “”)数据源名
@Configuration
@MapperScan(basePackages = "com.nk.db.data", sqlSessionFactoryRef = "dataSqlSessionFactory")
public class DataMyBatisConfig {
@Bean(name = "DataSource")
@ConfigurationProperties(prefix = "spring.datasource.data")
public DataSource testDataSource() {
return DataSourceBuilder.create().build();
}
@Bean(name="dataSqlSessionFactory")
public SqlSessionFactory testSqlSessionFactory(@Qualifier("DataSource") DataSource dataSource) throws Exception {
SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
bean.setDataSource(dataSource);
//读取mybatis小配置文件
bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mapping/data/*/*.xml"));
return bean.getObject();
}
@Bean(name = "dataTransactionManager")
public DataSourceTransactionManager testTransactionManager(@Qualifier("DataSource") DataSource dataSource) {
return new DataSourceTransactionManager(dataSource);
}
@Bean(name = "dataSqlSessionTemplate")
public SqlSessionTemplate testSqlSessionTemplate(@Qualifier("dataSqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
return new SqlSessionTemplate(sqlSessionFactory);
}
}
@Primary 默认读取的数据库
@MapperScan(basePackages = "com.nk.db.record", sqlSessionFactoryRef = "recordSqlSessionFactory")
public class RecordMyBataisConfig {
@Bean(name = "recordDataSource")
@ConfigurationProperties(prefix = "spring.datasource.record")
@Primary
public DataSource testDataSource() {
return DataSourceBuilder.create().build();
}
@Bean(name="recordSqlSessionFactory")
@Primary
public SqlSessionFactory testSqlSessionFactory(@Qualifier("recordDataSource") DataSource dataSource) throws Exception {
SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
bean.setDataSource(dataSource);
//读取mybatis小配置文件
bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mapping/record/*/*.xml"));
return bean.getObject();
}
@Bean(name = "recordTransactionManager")
@Primary
public DataSourceTransactionManager testTransactionManager(@Qualifier("recordDataSource") DataSource dataSource) {
return new DataSourceTransactionManager(dataSource);
}
@Bean(name = "recordSqlSessionTemplate")
@Primary
public SqlSessionTemplate testSqlSessionTemplate(@Qualifier("recordSqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
return new SqlSessionTemplate(sqlSessionFactory);
}
}