MyBatis-Plus 支持多数据源的配置,可以通过配置多个 DataSource 和 SqlSessionFactory 实例,并通过注解或配置文件指定使用哪个数据源。以下是一个简单的示例,演示如何在 Spring Boot 中配置多数据源:

1. 添加依赖: 在 Maven 或 Gradle 中添加 MyBatis-Plus 和数据库驱动的依赖。
<!-- Maven 依赖 -->
<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus-boot-starter</artifactId>
    <version>最新版本</version>
</dependency>

<!-- 数据库驱动依赖 -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
    <groupId>com.h2database</groupId>
    <artifactId>h2</artifactId>
    <scope>runtime</scope>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>

2. 配置多数据源: 在 application.yml 或 application.properties 中配置多个数据源的信息。
# 数据源1
spring.datasource.ds1.url=jdbc:mysql://localhost:3306/db1
spring.datasource.ds1.username=root
spring.datasource.ds1.password=root
spring.datasource.ds1.driver-class-name=com.mysql.cj.jdbc.Driver

# 数据源2
spring.datasource.ds2.url=jdbc:mysql://localhost:3306/db2
spring.datasource.ds2.username=root
spring.datasource.ds2.password=root
spring.datasource.ds2.driver-class-name=com.mysql.cj.jdbc.Driver

3. 创建多个 DataSource 和 SqlSessionFactory 实例: 在配置类中创建多个 DataSource 和 SqlSessionFactory 实例。
@Configuration
@MapperScan(basePackages = "com.example.mapper.ds1", sqlSessionFactoryRef = "sqlSessionFactory1")
public class DataSourceConfig1 {

    @Primary
    @Bean(name = "dataSource1")
    @ConfigurationProperties(prefix = "spring.datasource.ds1")
    public DataSource dataSource() {
        return DataSourceBuilder.create().build();
    }

    @Primary
    @Bean(name = "sqlSessionFactory1")
    public SqlSessionFactory sqlSessionFactory(@Qualifier("dataSource1") DataSource dataSource,
            ApplicationContext applicationContext) throws Exception {
        MybatisSqlSessionFactoryBean factoryBean = new MybatisSqlSessionFactoryBean();
        factoryBean.setDataSource(dataSource);
        factoryBean.setMapperLocations(new PathMatchingResourcePatternResolver()
                .getResources("classpath*:mapper/ds1/*.xml"));
        factoryBean.setConfigLocation(new ClassPathResource("mybatis-config.xml"));
        return factoryBean.getObject();
    }
}

在上述示例中,@Primary 注解表示这是默认的数据源。如果你有更多的数据源,可以创建类似的配置类,分别配置不同的数据源信息。

4. 在 Mapper 接口中指定数据源: 在需要使用的 Mapper 接口上使用 @DS 注解指定数据源。
@DS("ds1") // 指定数据源
public interface UserMapper1 extends BaseMapper<User> {
    // Mapper 方法
}

在这个示例中,@DS("ds1") 注解表示该 Mapper 使用名为 "ds1" 的数据源。

通过以上步骤,你就可以在 Spring Boot 项目中配置和使用多数据源了。请根据实际需要灵活配置数据源信息和指定数据源的方式。


转载请注明出处:http://www.zyzy.cn/article/detail/7066/MyBatis