在项目中,我们通常会进行数据库拆分或是引入其他数据库,从而我们需要配置多个数据源:
如何区分多个数据源:通过包来区分:com.db1.mapper com.db2.mapper
1.加入依赖
<!-- springboot集成mybatis -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.1</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
2.全局配置文件配置多个数据源
#SpringBoot整合多数据源
spring.datasource.db1.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.db1.username=root
spring.datasource.db1.password=root
spring.datasource.db1.url=jdbc:mysql://localhost:3306/db1
spring.datasource.db5.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.db5.username=root
spring.datasource.db5.password=root
spring.datasource.db5.url=jdbc:mysql://localhost:3306/db5
3.编写数据源
有多少个写多少个
如:
指定一个为默认数据源
@Primary:设置为默认数据源(每个方法都要写)
@Configuration//注册到Spring容器中
@MapperScan(basePackages="com.qianfeng.db1.mapper",sqlSessionFactoryRef="db1SqlSessionFactory")
public class DataSource1 {
//private DataSource1(){}
/**
* 配置db1数据库
* @return
*/
@Bean(name="db1Datasource")
@ConfigurationProperties(prefix="spring.datasource.db1")
public DataSource testDatasource() {
return DataSourceBuilder.create().build();
}
/**
* 创建SqlSessionFactory
* @param dataSource
* @return
* @throws Exception
*/
@Bean(name="db1SqlSessionFactory")
@Primary
public SqlSessionFactory testSqlSessionFactory(@Qualifier("db1Datasource")DataSource dataSource)
throws Exception {
SqlSessionFactoryBean bean=new SqlSessionFactoryBean();
bean.setDataSource(dataSource);
return bean.getObject();
}
/**
* 配置事务管理
* @param dataSource
* @return
*/
@Bean(name="db1TransactionManager")
public DataSourceTransactionManager testTransactionManager(
@Qualifier("db1Datasource")DataSource dataSource) {
return new DataSourceTransactionManager(dataSource);
}
@Bean(name="db1SqlSessionTemplate")
public SqlSessionTemplate testSqlSessionTemplate(@Qualifier("db1SqlSessionFactory")
SqlSessionFactory sqlSessionFactory) {
return new SqlSessionTemplate(sqlSessionFactory);
}
}
4.写mapper(通过包名区分,有多少个写多少个包)
如:
5.写service、controller
6.写启动类