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

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

项目结构

        Spring Boot 整合 MyBatis Plus实现多数据源的两种方式_第1张图片

 xml依赖:



    
        multi-datasource-parent
        com.ganbo
        1.0-SNAPSHOT
    

    4.0.0

    multi-datasource-config

    
        8
        8
    

    
        
            org.springframework.boot
            spring-boot-starter-web
        
        
        
            com.baomidou
            mybatis-plus-boot-starter
            3.3.1
        
        
        
            com.baomidou
            mybatis-plus-generator
            3.3.1.tmp
        
        
        
            mysql
            mysql-connector-java
            runtime
        
        
            org.springframework.boot
            spring-boot-starter-test
            test
        
        
            org.projectlombok
            lombok
            true
        
    

    
        
            
                org.springframework.boot
                spring-boot-maven-plugin
            
        
    

多数据源配置类(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实现多数据源的两种方式_第2张图片

  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依赖:

  
  
      com.baomidou
      dynamic-datasource-spring-boot-starter
      3.3.1
   

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 实现多数据源。

你可能感兴趣的:(Spring,spring,boot)