springboot mybits 配置多数据源
时间: 2023-09-09 18:03:25 浏览: 106
在SpringBoot中配置多数据源,我们需要完成以下步骤:
1. 引入MyBatis和多数据源依赖:在pom.xml文件中添加如下依赖:
```xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
</dependency>
```
2. 配置数据源:在application.properties(或application.yml)文件中配置多个数据源信息,例如:
```properties
# 数据源1配置
spring.datasource.url=jdbc:mysql://localhost:3306/db1
spring.datasource.username=username
spring.datasource.password=password
# 数据源2配置
datasource.db2.url=jdbc:mysql://localhost:3306/db2
datasource.db2.username=username
datasource.db2.password=password
```
3. 创建数据源实例:在@Configuration类中创建多个数据源的实例,并配置为Spring的Bean。例如:
```java
@Configuration
public class DataSourceConfig {
@Bean
@ConfigurationProperties(prefix = "spring.datasource")
public DataSource primaryDataSource() {
return DataSourceBuilder.create().build();
}
@Bean
@ConfigurationProperties(prefix = "datasource.db2")
public DataSource secondaryDataSource() {
return DataSourceBuilder.create().build();
}
}
```
4. 创建SqlSessionFactory:创建多个SqlSessionFactory对象,并分别关联对应的DataSource。例如:
```java
@Configuration
@MapperScan(basePackages = "com.example.mapper.db1", sqlSessionFactoryRef = "primarySqlSessionFactory")
public class MybatisConfig1 {
@Autowired
@Qualifier("primaryDataSource")
private DataSource primaryDataSource;
@Bean
public SqlSessionFactory primarySqlSessionFactory() throws Exception {
SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
factoryBean.setDataSource(primaryDataSource);
return factoryBean.getObject();
}
}
@Configuration
@MapperScan(basePackages = "com.example.mapper.db2", sqlSessionFactoryRef = "secondarySqlSessionFactory")
public class MybatisConfig2 {
@Autowired
@Qualifier("secondaryDataSource")
private DataSource secondaryDataSource;
@Bean
public SqlSessionFactory secondarySqlSessionFactory() throws Exception {
SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
factoryBean.setDataSource(secondaryDataSource);
return factoryBean.getObject();
}
}
```
5. 在Mapper接口中指定使用的SqlSessionFactory:在每个Mapper接口上使用注解@Mapper以及@Qualifier指定使用的SqlSessionFactory。例如:
```java
@Mapper
@Qualifier("primarySqlSessionFactory")
public interface UserMapper {
// ...
}
@Mapper
@Qualifier("secondarySqlSessionFactory")
public interface OrderMapper {
// ...
}
```
通过以上配置,我们成功配置了多数据源的SpringBoot项目,可以分别使用不同的数据源进行数据访问操作。
阅读全文