Springboot整合了Mybatis,mybatis-config.xml可以省略不写,如何配置多数据源
时间: 2023-12-10 13:39:17 浏览: 102
在Spring Boot中,配置多数据源可以通过以下步骤实现:
1. 在`application.properties`或`application.yml`中配置多个数据源的相关属性,例如:
```yml
spring:
datasource:
master:
url: jdbc:mysql://localhost:3306/master_db
username: root
password: root
driver-class-name: com.mysql.jdbc.Driver
slave:
url: jdbc:mysql://localhost:3306/slave_db
username: root
password: root
driver-class-name: com.mysql.jdbc.Driver
```
2. 创建多个数据源的实例,并将它们注入到`SqlSessionFactory`中:
```java
@Configuration
public class MybatisConfig {
@Bean
@ConfigurationProperties(prefix = "spring.datasource.master")
public DataSource masterDataSource() {
return DataSourceBuilder.create().build();
}
@Bean
@ConfigurationProperties(prefix = "spring.datasource.slave")
public DataSource slaveDataSource() {
return DataSourceBuilder.create().build();
}
@Bean
public SqlSessionFactory masterSqlSessionFactory(@Qualifier("masterDataSource") DataSource dataSource) throws Exception {
SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
factoryBean.setDataSource(dataSource);
return factoryBean.getObject();
}
@Bean
public SqlSessionFactory slaveSqlSessionFactory(@Qualifier("slaveDataSource") DataSource dataSource) throws Exception {
SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
factoryBean.setDataSource(dataSource);
return factoryBean.getObject();
}
}
```
3. 配置`@MapperScan`注解扫描多个`Mapper`接口所在的包路径,并指定对应的`SqlSessionFactory`:
```java
@Configuration
@MapperScan(basePackages = "com.example.mapper.master", sqlSessionFactoryRef = "masterSqlSessionFactory")
public class MasterDataSourceConfig {
}
@Configuration
@MapperScan(basePackages = "com.example.mapper.slave", sqlSessionFactoryRef = "slaveSqlSessionFactory")
public class SlaveDataSourceConfig {
}
```
这样就可以在应用中使用多个数据源了。在需要访问不同数据源的`Mapper`接口方法上,可以使用`@Qualifier`注解指定对应的`SqlSessionFactory`,例如:
```java
@Service
public class UserService {
@Autowired
@Qualifier("masterSqlSessionFactory")
private SqlSessionFactory masterSqlSessionFactory;
@Autowired
@Qualifier("slaveSqlSessionFactory")
private SqlSessionFactory slaveSqlSessionFactory;
public User getMasterUserById(int id) {
try (SqlSession sqlSession = masterSqlSessionFactory.openSession()) {
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
return userMapper.getById(id);
}
}
public User getSlaveUserById(int id) {
try (SqlSession sqlSession = slaveSqlSessionFactory.openSession()) {
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
return userMapper.getById(id);
}
}
}
```
阅读全文