springboot整合mybatis多数据源,使用mapper接口查询数据,sql放在xml中,给出具体代码
时间: 2023-05-15 09:05:03 浏览: 108
以下是使用 Spring Boot 整合 MyBatis 多数据源,使用 Mapper 接口查询数据,SQL 放在 XML 中的示例代码:
首先,在 `application.properties` 中配置数据源:
```
# 主数据源
spring.datasource.primary.url=jdbc:mysql://localhost:3306/db1
spring.datasource.primary.username=root
spring.datasource.primary.password=root
# 第二个数据源
spring.datasource.secondary.url=jdbc:mysql://localhost:3306/db2
spring.datasource.secondary.username=root
spring.datasource.secondary.password=root
```
然后,定义两个数据源的 `DataSource` 对象:
```java
@Configuration
public class DataSourceConfig {
@Bean
@Primary
@ConfigurationProperties(prefix = "spring.datasource.primary")
public DataSource primaryDataSource() {
return DataSourceBuilder.create().build();
}
@Bean
@ConfigurationProperties(prefix = "spring.datasource.secondary")
public DataSource secondaryDataSource() {
return DataSourceBuilder.create().build();
}
}
```
接下来,定义两个 `SqlSessionFactory` 对象,分别使用不同的数据源:
```java
@Configuration
@MapperScan(basePackages = "com.example.mapper.primary", sqlSessionFactoryRef = "primarySqlSessionFactory")
public class PrimaryDataSourceConfig {
@Bean
@Primary
public SqlSessionFactory primarySqlSessionFactory(@Qualifier("primaryDataSource") DataSource dataSource) throws Exception {
SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
bean.setDataSource(dataSource);
bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath*:mapper/primary/*.xml"));
return bean.getObject();
}
}
@Configuration
@MapperScan(basePackages = "com.example.mapper.secondary", sqlSessionFactoryRef = "secondarySqlSessionFactory")
public class SecondaryDataSourceConfig {
@Bean
public SqlSessionFactory secondarySqlSessionFactory(@Qualifier("secondaryDataSource") DataSource dataSource) throws Exception {
SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
bean.setDataSource(dataSource);
bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath*:mapper/secondary/*.xml"));
return bean.getObject();
}
}
```
最后,定义两个 `Mapper` 接口,分别使用不同的 `SqlSessionFactory`:
```java
@Mapper
public interface PrimaryMapper {
@Select("SELECT * FROM table1 WHERE id = #{id}")
Table1 getById(@Param("id") Long id);
}
@Mapper
public interface SecondaryMapper {
@Select("SELECT * FROM table2 WHERE id = #{id}")
Table2 getById(@Param("id") Long id);
}
```
这样,就可以在不同的 `Mapper` 接口中使用不同的数据源和 SQL 语句了。
阅读全文