Spring Boot 整合 MyBatis Plus实现多数据源的两种方式

时间:2022-11-19 12:55:02

第一种:使用配置类的方式:

项目结构

        Spring Boot 整合 MyBatis Plus实现多数据源的两种方式

 xml依赖:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>multi-datasource-parent</artifactId>
        <groupId>com.ganbo</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>

    <modelVersion>4.0.0</modelVersion>

    <artifactId>multi-datasource-config</artifactId>

    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!-- mybatis-plus -->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.3.1</version>
        </dependency>
        <!-- mybatis-plus代码生成器 -->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-generator</artifactId>
            <version>3.3.1.tmp</version>
        </dependency>
        <!-- mysql连接 -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

多数据源配置类(DataSource -> SqlsessionFactory -> SqlSessionTemplate -> DataSourceTransactionManager)

DataSourceUserConfig 配置类:

package com.multidb.configdemo.config;

import com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;

@Configuration
@MapperScan(basePackages = "com.multidb.configdemo.dao.user", sqlSessionTemplateRef = "userSqlSessionTemplate")
public class DataSourceUserConfig {


    @Primary //设置主数据源
    @Bean(name = "userDataSource")
    @ConfigurationProperties(prefix = "spring.datasource.user")
    public DataSource userDataSource() {
        return DataSourceBuilder.create().build();
    }

    @Bean(name = "userSqlSessionFactory")
    public SqlSessionFactory userSqlSessionFactory(@Qualifier("userDataSource") DataSource dataSource) throws Exception {

        //工厂bean  SqlSessionFactory
        MybatisSqlSessionFactoryBean bean = new MybatisSqlSessionFactoryBean();

        //设置数据源
        bean.setDataSource(dataSource);

        //加载映射文件
        bean.setMapperLocations(new PathMatchingResourcePatternResolver().
                getResources("classpath*:mapper/user/*.xml"));
        return bean.getObject();
    }

    // 数据源事务管理器
    public DataSourceTransactionManager db1TransactionManager(@Qualifier("userDataSource") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }

    @Bean(name = "userSqlSessionTemplate")
    public SqlSessionTemplate userSqlSessionTemplate(@Qualifier("userSqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
        return new SqlSessionTemplate(sqlSessionFactory);
    }

}

DataSourceOrderConfig 配置类:

package com.multidb.configdemo.config;

import com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;


@Configuration
@MapperScan(basePackages = "com.multidb.configdemo.dao.order", sqlSessionTemplateRef = "orderSqlSessionTemplate")
public class DataSourceOrderConfig {


//    @Primary
    @Bean(name = "orderDataSource")
    @ConfigurationProperties(prefix = "spring.datasource.order")
    public DataSource orderDataSource() {
        return DataSourceBuilder.create().build();
    }

    @Bean(name = "orderSqlSessionFactory")
    public SqlSessionFactory orderSqlSessionFactory(@Qualifier("orderDataSource") DataSource dataSource) throws Exception {

        //工厂bean  SqlSessionFactory
        MybatisSqlSessionFactoryBean bean = new MybatisSqlSessionFactoryBean();

        //设置数据源
        bean.setDataSource(dataSource);

        //加载映射文件
        bean.setMapperLocations(new PathMatchingResourcePatternResolver().
                getResources("classpath*:mapper/order/*.xml"));
        return bean.getObject();
    }

    // 数据源事务管理器
    public DataSourceTransactionManager db1TransactionManager(@Qualifier("orderDataSource") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }

    @Bean(name = "orderSqlSessionTemplate")
    public SqlSessionTemplate orderSqlSessionTemplate(@Qualifier("orderSqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
        return new SqlSessionTemplate(sqlSessionFactory);
    }

}

多个mapper接口:

Spring Boot 整合 MyBatis Plus实现多数据源的两种方式

  application.properties 配置文件


spring:
  datasource:
    user:
      driver-class-name: com.mysql.cj.jdbc.Driver
      username: root
      password: root
      jdbc-url: jdbc:mysql://127.0.0.1:3306/user?useUnicode=true&characterEncoding=utf-8&serverTimezone=UTC&useSSL=false
    order:
      driver-class-name: com.mysql.cj.jdbc.Driver
      username: root
      password: root
      jdbc-url: jdbc:mysql://127.0.0.1:3306/order?useUnicode=true&characterEncoding=utf-8&serverTimezone=UTC&useSSL=false

mybatis-plus:
#  mapper-locations: classpath:mapper/*.xml # xml文件路径
  configuration:
    map-underscore-to-camel-case: true  # 驼峰转换
    cache-enabled: false  # 是否开启缓存
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl # 打印sql
#  global-config: # 全局配置
#    db-column-underline: true  # 数据库字段驼峰下划线转换
#    id-type: 0 # id自增类型(数据库id自增)

第二种:使用@DS 注解 切换数据源

新增pom依赖:

  <!-- Mybatis plus多数据源支持,版本与 mybatis-plus保存一致 -->
  <dependency>
      <groupId>com.baomidou</groupId>
      <artifactId>dynamic-datasource-spring-boot-starter</artifactId>
      <version>3.3.1</version>
   </dependency>

application.yml 配置



spring:
  datasource:
    dynamic:
      primary: user #设置默认的数据源或者数据源组,默认值即为master
      strict: false #严格匹配数据源,默认false. true未匹配到指定数据源时抛异常,false使用默认数据源
      datasource:
        user:
          url: jdbc:mysql://127.0.0.1:3306/user?useUnicode=true&characterEncoding=utf-8&serverTimezone=UTC&useSSL=false
          username: root
          password: root
          driver-class-name: com.mysql.jdbc.Driver #3.2.0开始支持SPI可省略此配置
        order:
          url: jdbc:mysql://127.0.0.1:3306/order?useUnicode=true&characterEncoding=utf-8&serverTimezone=UTC&useSSL=false
          username: root
          password: root
          driver-class-name: com.mysql.jdbc.Driver


mybatis-plus:
  mapper-locations: classpath:mapper/**/*.xml #xml文件路径
  configuration:
    map-underscore-to-camel-case: true  #驼峰转换
    cache-enabled: false  #是否开启缓存
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl #打印sql
  # global-config: #全局配置
  #   db-column-underline: true  #数据库字段驼峰下划线转换
  #   id-type: 0 #id自增类型(数据库id自增)

添加 @DS注解 切换数据源


import com.baomidou.dynamic.datasource.annotation.DS;
import com.multidb.annotationdemo.dao.order.OrderDao;
import com.multidb.annotationdemo.entity.order.Order;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
@DS("order")
public class OrderService {

    @Autowired
    OrderDao orderDao;

    public Order getOrder() {
        return orderDao.selectByPrimaryKey(1L);
    }

}
package com.multidb.annotationdemo.service;


import com.baomidou.dynamic.datasource.annotation.DS;
import com.multidb.annotationdemo.dao.user.UserDao;
import com.multidb.annotationdemo.entity.user.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
@DS("user")
public class UserService {

    @Autowired
    UserDao userDao;

    public User getUser() {
        return userDao.selectByPrimaryKey(1L);
    }

}

启动类配置扫描mapper接口:

@SpringBootApplication
@MapperScan("com.multidb.annotationdemo.dao.**")
public class Datasource1Application {

    public static void main(String[] args) {
        SpringApplication.run(Datasource1Application.class, args);
    }

}

测试

@RestController
public class IndexController {

    @Autowired
    UserService userService;
    @Autowired
    OrderService orderService;

    @GetMapping("/getUser")
    public User getUser() {
        return userService.getUser();
    }

    @GetMapping("/getOrder")
    public Order getOrder() {
        return orderService.getOrder();
    }

}

项目源码以及数据库脚本: multi-datasource-parent: Spring boot 整合 MyBatis 实现多数据源。