// 主数据源配置如下:
/**
* @Description 主数据源配置
* @Author Tree
* @Date 2019/6/28
* @Version V2.0
**/
//表示这个类为一个配置类
@Configuration
// 配置mybatis的接口类放的地方
@MapperScan(basePackages = "com.bojun.mimuapp.dao.primary", sqlSessionFactoryRef = "primarySqlSessionFactory")
public class DataSourceConfig1 {
// 将这个对象放入Spring容器中
@Bean(name = "primaryDataSource")
// 表示这个数据源是默认数据源
@Primary
// 读取application.yml中的配置参数映射成为一个对象
// prefix表示参数的前缀
@ConfigurationProperties(prefix = "spring.datasource.primary")
public DataSource getDateSource1() {
return DataSourceBuilder.create().build();
}
@Bean(name = "primarySqlSessionFactory")
// 表示这个数据源是默认数据源
@Primary
// @Qualifier表示查找Spring容器中名字为primaryDataSource的对象
public SqlSessionFactory primarySqlSessionFactory(@Qualifier("primaryDataSource") DataSource datasource)
throws Exception {
SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
bean.setDataSource(datasource);
bean.setMapperLocations(
// 设置mybatis的xml所在位置
new PathMatchingResourcePatternResolver().getResources("classpath:mapper/primary/*.xml"));
return bean.getObject();
}
@Bean("primarySqlSessionTemplate")
// 表示这个数据源是默认数据源
@Primary
public SqlSessionTemplate primarySqlsessiontemplate(
@Qualifier("primarySqlSessionFactory") SqlSessionFactory sessionfactory) {
return new SqlSessionTemplate(sessionfactory);
}
}
// 次数据源配置如下:
/**
* @Description 次数据源配置
* @Author Tree
* @Date 2019/6/28
* @Version V2.0
**/
@Configuration
@MapperScan(basePackages = "com.bojun.mimuapp.dao.secondary", sqlSessionFactoryRef = "secondarySqlSessionFactory")
public class DataSourceConfig2 {
@Bean(name = "secondaryDataSource")
@ConfigurationProperties(prefix = "spring.datasource.secondary")
public DataSource getDateSource2() {
return DataSourceBuilder.create().build();
}
@Bean(name = "secondarySqlSessionFactory")
public SqlSessionFactory secondarySqlSessionFactory(@Qualifier("secondaryDataSource") DataSource datasource)
throws Exception {
SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
bean.setDataSource(datasource);
bean.setMapperLocations(
new PathMatchingResourcePatternResolver().getResources("classpath:mapper/secondary/*.xml"));
return bean.getObject();
}
@Bean("secondarySqlSessionTemplate")
public SqlSessionTemplate secondarySqlsessiontemplate(
@Qualifier("secondarySqlSessionFactory") SqlSessionFactory sessionfactory) {
return new SqlSessionTemplate(sessionfactory);
}
}
// 配置文件数据库多数据源配置如下:
server:
port: 8896
spring:
datasource:
primary:
jdbc-url: jdbc:sqlserver://xxxxxxxxx;databaseName=xxxxxx
username: sa
password: xxxxxx
driver-class-name: com.microsoft.sqlserver.jdbc.SQLServerDriver
secondary:
jdbc-url: jdbc:sqlserver://XXXXX;databaseName=XXXXXXX
username: sa
password: xxxxxxx
driver-class-name: com.microsoft.sqlserver.jdbc.SQLServerDriver
// 具体的多数据源的简单用法如下:在同一个service层分别注入多个数据源的mapper,并使用不同数据源注入进来的mapper实现对不通数据库的操作
// 测试通过注入进来的不同的数据源的mapper实现对不同数据库的插入数据操作如下:
// dao层目录结构如下:
// xml文件目录如下:
// 最后附上springboot中的一些常用注解的使用说明参考文章:https://blog.csdn.net/tuesdayma/article/details/81029539