application-dev.yml配置
spring:
datasource:
## 源数据库
db1:
jdbc-url: jdbc:mysql://IP:port/databaseName?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai
username: root
password:
## 目标数据库
db2:
jdbc-url: jdbc:mysql://IP:port/databaseName?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai
username: root
password:
主数据源配置
多数据源的原理是根据不同包,调用不同的数据源,只要把不同数据源的mapper.java和mapper.xml分别写在不同的包里,通过@MapperScan扫描不同的包就可以自动实现。
@Configuration
@MapperScan(basePackages = "cn.com.ticketService.mapper.origin", sqlSessionFactoryRef = "originSqlSessionFactory")
public class DataSourceConfigOrigin {
// 将这个对象放入Spring容器中
@Bean(name = "originDataSource")
// 表示这个数据源是默认数据源
@Primary
// 读取application.properties中的配置参数映射成为一个对象、prefix表示参数的前缀
@ConfigurationProperties(prefix = "spring.datasource.db1")
public DataSource getDateSource1() {
return DataSourceBuilder.create().build();
}
@Bean(name = "originSqlSessionFactory")
// 表示这个数据源是默认数据源
@Primary
// @Qualifier表示查找Spring容器中名字为test1DataSource的对象
public SqlSessionFactory originSqlSessionFactory(@Qualifier("originDataSource") DataSource datasource) throws Exception {
SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
bean.setDataSource(datasource);
bean.setMapperLocations(
// 设置mybatis的xml所在位置
new PathMatchingResourcePatternResolver().getResources("classpath*:mybatis/origin/*.xml"));
return bean.getObject();
}
@Bean("test1SqlSessionTemplate")
// 表示这个数据源是默认数据源
@Primary
public SqlSessionTemplate originSqlSessionTemplate(
@Qualifier("originSqlSessionFactory") SqlSessionFactory sessionfactory) {
return new SqlSessionTemplate(sessionfactory);
}
}
从数据源配置
@Configuration
@MapperScan(basePackages = "cn.com.ticketService.mapper.target", sqlSessionFactoryRef = "targetSqlSessionFactory")
public class DataSourceConfigTarget {
@Bean(name = "targetDataSource")
@ConfigurationProperties(prefix = "spring.datasource.db2")
public DataSource getDateSource2() {
return DataSourceBuilder.create().build();
}
@Bean(name = "targetSqlSessionFactory")
public SqlSessionFactory targetSqlSessionFactory(@Qualifier("targetDataSource") DataSource datasource)
throws Exception {
SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
bean.setDataSource(datasource);
bean.setMapperLocations(
new PathMatchingResourcePatternResolver().getResources("classpath*:mybatis/target/*.xml"));
return bean.getObject();
}
@Bean("test2SqlSessionTemplate")
public SqlSessionTemplate targetSqlSessionTemplate(
@Qualifier("targetSqlSessionFactory") SqlSessionFactory sessionfactory) {
return new SqlSessionTemplate(sessionfactory);
}
}
包结构
cn.com.ticketService
--mapper
----origin
----target
resource结构
----application.yml
----application-dev.yml
----mybatis
------origin
------target