springboot整合mybatis多数据源,使用mapper接口查询数据,给出具体代码
时间: 2023-05-15 17:05:00 浏览: 170
好的,以下是一个简单的示例代码:
首先,在 application.properties 文件中配置数据源:
```
# 数据源1
spring.datasource.url=jdbc:mysql://localhost:3306/db1
spring.datasource.username=root
spring.datasource.password=123456
# 数据源2
spring.datasource.db2.url=jdbc:mysql://localhost:3306/db2
spring.datasource.db2.username=root
spring.datasource.db2.password=123456
```
然后,在代码中定义两个数据源:
```
@Configuration
public class DataSourceConfig {
@Bean(name = "dataSource1")
@ConfigurationProperties(prefix = "spring.datasource")
public DataSource dataSource1() {
return DataSourceBuilder.create().build();
}
@Bean(name = "dataSource2")
@ConfigurationProperties(prefix = "spring.datasource.db2")
public DataSource dataSource2() {
return DataSourceBuilder.create().build();
}
}
```
接着,在 Mybatis 的配置文件中配置两个 SqlSessionFactory:
```
@Configuration
@MapperScan(basePackages = "com.example.mapper1", sqlSessionFactoryRef = "sqlSessionFactory1")
public class MybatisConfig1 {
@Autowired
@Qualifier("dataSource1")
private DataSource dataSource1;
@Bean(name = "sqlSessionFactory1")
public SqlSessionFactory sqlSessionFactory1() throws Exception {
SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
factoryBean.setDataSource(dataSource1);
return factoryBean.getObject();
}
}
@Configuration
@MapperScan(basePackages = "com.example.mapper2", sqlSessionFactoryRef = "sqlSessionFactory2")
public class MybatisConfig2 {
@Autowired
@Qualifier("dataSource2")
private DataSource dataSource2;
@Bean(name = "sqlSessionFactory2")
public SqlSessionFactory sqlSessionFactory2() throws Exception {
SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
factoryBean.setDataSource(dataSource2);
return factoryBean.getObject();
}
}
```
最后,在 Mapper 接口中使用 @Qualifier 注解指定使用哪个 SqlSessionFactory:
```
@Mapper
@Qualifier("sqlSessionFactory1")
public interface Mapper1 {
// ...
}
@Mapper
@Qualifier("sqlSessionFactory2")
public interface Mapper2 {
// ...
}
```
以上就是整合 Spring Boot 和 Mybatis 多数据源的示例代码。
阅读全文