配置文件
datasource:
base:
driver-class-name: com.mysql.jdbc.Driver
password: root
url: jdbc:mysql://10.10.10.236:3306/hotdog?useUnicode=true&characterEncoding=utf8&useSSL=false
username: root
test-on-borrow: true
test-while-idle: true
yr:
driver-class-name: com.microsoft.sqlserver.jdbc.SQLServerDriver
password: root
url: jdbc:sqlserver://127.0.0.1;database=smarthone_sy
username: root
test-on-borrow: true
test-while-idle: true
DataSourceConfig
@Configuration
public class DataSourceConfig {
@Bean(name = "base")
@Primary
@ConfigurationProperties(prefix = "spring.datasource.base") // application.properteis中对应属性的前缀
public DataSource dataSource1() {
return DataSourceBuilder.create().build();
}
@Bean(name = "yr")
@ConfigurationProperties(prefix = "spring.datasource.yr") // application.properteis中对应属性的前缀
public DataSource dataSource2() {
return DataSourceBuilder.create().build();
}
}
db1
@Configuration
@MapperScan(basePackages = {"cn.xydata.mapper"}, sqlSessionFactoryRef = "sqlSessionFactory1")
public class MybatisDbAConfig {
@Autowired
@Qualifier("base")
private DataSource ds1;
@Bean
public SqlSessionFactory sqlSessionFactory1() throws Exception {
SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
factoryBean.setDataSource(ds1); // 使用titan数据源, 连接titan库
return factoryBean.getObject();
}
@Bean
public SqlSessionTemplate sqlSessionTemplate1() throws Exception {
SqlSessionTemplate template = new SqlSessionTemplate(sqlSessionFactory1()); // 使用上面配置的Factory
return template;
}
}
db2
@Configuration
@MapperScan(basePackages = {"cn.xydata.mapper2"}, sqlSessionFactoryRef = "sqlSessionFactory2")
public class MybatisDbAConfig2 {
@Autowired
@Qualifier("yr")
private DataSource ds1;
@Bean
public SqlSessionFactory sqlSessionFactory2() throws Exception {
SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
factoryBean.setDataSource(ds1); // 使用titan数据源, 连接titan库
return factoryBean.getObject();
}
@Bean
public SqlSessionTemplate sqlSessionTemplate2() throws Exception {
SqlSessionTemplate template = new SqlSessionTemplate(sqlSessionFactory2()); // 使用上面配置的Factory
return template;
}
}
最后在对应的包下放置mapper类