mybatisplus双数据源配置mapper
时间: 2024-09-14 14:16:13 浏览: 41
MyBatis-Plus是一个MyBatis的增强工具,在MyBatis的基础上只做增强不做改变,为简化开发、提高效率而生。在一些复杂的应用场景中,可能需要配置多个数据源,例如同时连接MySQL和Oracle数据库。双数据源配置通常涉及到Spring Boot的配置文件以及MyBatis-Plus的配置类。
以下是一个简单的双数据源配置MyBatis-Plus的mapper的示例:
1. 首先,在`application.properties`或`application.yml`文件中配置两个数据源:
```properties
# 第一个数据源配置
spring.datasource.druid.primary.url=jdbc:mysql://localhost:3306/primary_db
spring.datasource.druid.primary.username=root
spring.datasource.druid.primary.password=123456
spring.datasource.druid.primary.driver-class-name=com.mysql.cj.jdbc.Driver
# 第二个数据源配置
spring.datasource.druid.secondary.url=jdbc:oracle:thin:@localhost:1521:orcl
spring.datasource.druid.secondary.username=secondary_user
spring.datasource.druid.secondary.password=654321
spring.datasource.druid.secondary.driver-class-name=oracle.jdbc.driver.OracleDriver
```
2. 创建两个数据源的配置类:
```java
@Configuration
@MapperScan(basePackages = "com.example.mapper.primary", sqlSessionTemplateRef = "primarySqlSessionTemplate")
public class PrimaryDataSourceConfig {
@Bean(name = "primaryDataSource")
@ConfigurationProperties(prefix = "spring.datasource.druid.primary")
public DataSource dataSource() {
return DruidDataSourceBuilder.create().build();
}
@Bean(name = "primarySqlSessionFactory")
public SqlSessionFactory sqlSessionFactory(@Qualifier("primaryDataSource") DataSource dataSource) throws Exception {
SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
bean.setDataSource(dataSource);
return bean.getObject();
}
@Bean(name = "primarySqlSessionTemplate")
public SqlSessionTemplate sqlSessionTemplate(@Qualifier("primarySqlSessionFactory") SqlSessionFactory sqlSessionFactory) {
return new SqlSessionTemplate(sqlSessionFactory);
}
}
@Configuration
@MapperScan(basePackages = "com.example.mapper.secondary", sqlSessionTemplateRef = "secondarySqlSessionTemplate")
public class SecondaryDataSourceConfig {
@Bean(name = "secondaryDataSource")
@ConfigurationProperties(prefix = "spring.datasource.druid.secondary")
public DataSource dataSource() {
return DruidDataSourceBuilder.create().build();
}
@Bean(name = "secondarySqlSessionFactory")
public SqlSessionFactory sqlSessionFactory(@Qualifier("secondaryDataSource") DataSource dataSource) throws Exception {
SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
bean.setDataSource(dataSource);
return bean.getObject();
}
@Bean(name = "secondarySqlSessionTemplate")
public SqlSessionTemplate sqlSessionTemplate(@Qualifier("secondarySqlSessionFactory") SqlSessionFactory sqlSessionFactory) {
return new SqlSessionTemplate(sqlSessionFactory);
}
}
```
3. 创建对应的mapper接口:
```java
@Mapper
public interface PrimaryMapper {
// 定义与primary_db数据库交互的方法
}
@Mapper
public interface SecondaryMapper {
// 定义与secondary_db数据库交互的方法
}
```
通过上述配置,你可以在应用中同时操作两个数据源,分别通过`PrimaryMapper`和`SecondaryMapper`来访问各自的数据库。
阅读全文