1.application.properties 中的配置
spring.datasource.one.url=jdbc:mysql:///test01? useUnicode=true&characterEncoding=utf-8
spring.datasource.one.username=root
spring.datasource.one.password=root
spring.datasource.one.type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.two.url=jdbc:mysql:///test02? useUnicode=true&characterEncoding=utf-8
spring.datasource.two.username=root
spring.datasource.two.password=root
spring.datasource.two.type=com.alibaba.druid.pool.DruidDataSource
2.DataSourceConfig
@Configuration public class DataSourceConfig {
@Bean
@ConfigurationProperties(prefix = "spring.datasource.one")
DataSource dsOne() {
return DruidDataSourceBuilder.create().build();
}
@Bean @ConfigurationProperties(prefix = "spring.datasource.two")
DataSource dsTwo() {
return DruidDataSourceBuilder.create().build();
}
}
3.MyBatis 配置
配置数据源1-----------先获得SqlSessionFactory —>再设置SqlSessionTemplate
@Configuration
@MapperScan(basePackages = "org.javaboy.mybatis.mapper1",sqlSessionFactoryRef = "sqlSessionFactory1",sqlSessionTemplateRef = "sqlSessionTemplate1")
public class MyBatisConfigOne {
@Resource(name = "dsOne")
DataSource dsOne;
@Bean SqlSessionFactory sqlSessionFactory1() {
SqlSessionFactory sessionFactory = null;
try {
SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
bean.setDataSource(dsOne);
sessionFactory = bean.getObject();
}
catch (Exception e) {
e.printStackTrace( );
}
return sessionFactory;
}
@Bean SqlSessionTemplate sqlSessionTemplate1() {
return new SqlSessionTemplate(sqlSessionFactory1());
}
}
配置数据源2
@Configuration
@MapperScan(basePackages = "org.javaboy.mybatis.mapper2",sqlSessionFactoryRef = "sqlSessionFactory2",sqlSessionTemplateRef = "sqlSessionTemplate2")
public class MyBatisConfigTwo {
@Resource(name = "dsTwo")
DataSource dsTwo;
@Bean SqlSessionFactory sqlSessionFactory2() {
SqlSessionFactory sessionFactory = null;
try {
SqlSessionFactoryBean bean = new
SqlSessionFactoryBean();
bean.setDataSource(dsTwo);
sessionFactory = bean.getObject();
}
catch (Exception e) {
e.printStackTrace( );
}
return sessionFactory;
}
@Bean SqlSessionTemplate sqlSessionTemplate2() {
return new SqlSessionTemplate(sqlSessionFactory2());
}
这样 MyBatis 多数据源基本上就配置好了,接下来只需要在 org.javaboy.mybatis.mapper1 和 org.javaboy.mybatis.mapper2 包中提供不同的 Mapper,Service 中注入不同的 Mapper 就可以操 作 不同的数据源。