• SpringBoot实现多数据源(四)【集成多个 Mybatis 框架】


    上一篇文章SpringBoot实现多数据源(三)【AOP + 自定义注解】

    四、集成多个 Mybatis 框架


    在这里插入图片描述

    实现步骤

    1. 创建一个 dynamic_mybatis 的springboot项目,导入依赖
      • pom.xml
    <dependencies>
        
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-jdbcartifactId>
        dependency>
        
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-webartifactId>
        dependency>
        
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-aopartifactId>
        dependency>
        
        <dependency>
            <groupId>org.mybatis.spring.bootgroupId>
            <artifactId>mybatis-spring-boot-starterartifactId>
            <version>2.1.4version>
        dependency>
        
        <dependency>
            <groupId>com.alibabagroupId>
            <artifactId>druid-spring-boot-starterartifactId>
            <version>1.2.8version>
        dependency>
        
        <dependency>
            <groupId>mysqlgroupId>
            <artifactId>mysql-connector-javaartifactId>
            <version>8.0.28version>
        dependency>
        
        <dependency>
            <groupId>org.projectlombokgroupId>
            <artifactId>lombokartifactId>
            <version>1.18.24version>
        dependency>
    
    dependencies>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    1. 配置文件
      • application.yml
    spring:
      application:
        name: dynamic_datasource
      # 数据源
      datasource:
        type: com.alibaba.druid.pool.DruidDataSource
        # 读数据源
        read:
          driver-class-name: com.mysql.cj.jdbc.Driver
          url: jdbc:mysql://localhost:3306/read?useSSL=true&useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai
          username: root
          password: 123456
        # 写数据源
        write:
          type: com.alibaba.druid.pool.DruidDataSource
          driver-class-name: com.mysql.cj.jdbc.Driver
          url: jdbc:mysql://localhost:3306/write?useSSL=true&useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai
          username: root
          password: 123456
    # 端口号
    server:
      port: 3355
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    1. 实体类(这里省略增删查改的数据库操作)
      • People
    package com.vinjcent.pojo;
    
    import lombok.AllArgsConstructor;
    import lombok.Data;
    import lombok.NoArgsConstructor;
    
    @AllArgsConstructor
    @NoArgsConstructor
    @Data
    public class People {
    
        private String name;
    
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    1. 配置读写分离的的MybatisConfiguration配置
    • RMybatisConfiguration(读数据源)
    package com.vinjcent.config.mybatis;
    
    import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder;
    import org.apache.ibatis.logging.stdout.StdOutImpl;
    import org.apache.ibatis.session.SqlSessionFactory;
    import org.mybatis.spring.SqlSessionFactoryBean;
    import org.mybatis.spring.annotation.MapperScan;
    import org.springframework.beans.factory.annotation.Qualifier;
    import org.springframework.boot.context.properties.ConfigurationProperties;
    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 javax.sql.DataSource;
    
    
    /**
     * 读数据源配置
     * 1. 指定扫描mapper接口包
     * 2. 指定使用wSqlSessionFactory是哪个
     */
    @Configuration
    @MapperScan(basePackages = "com.vinjcent.mapper.read", sqlSessionFactoryRef = "rSqlSessionFactory")
    public class RMybatisConfiguration {
    
    
        @Bean(name = "readDatasource")
        @ConfigurationProperties(prefix = "spring.datasource.read")
        public DataSource readDatasource() {
            // 底层会自动拿到spring.datasource中的配置,创建一个DruidDataSource
            return DruidDataSourceBuilder.create().build();
        }
    
        @Bean
        @Primary
        public SqlSessionFactory rSqlSessionFactory(@Qualifier("readDatasource") DataSource dataSource) throws Exception {
            final SqlSessionFactoryBean sqlSessionFactory = new SqlSessionFactoryBean();
            sqlSessionFactory.setDataSource(dataSource);
            sqlSessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver()
                    .getResources("classpath:com/vinjcent/mapper/read/*.xml"));
            /* 主库设置sql控制台打印 */
            org.apache.ibatis.session.Configuration configuration = new org.apache.ibatis.session.Configuration();
            configuration.setLogImpl(StdOutImpl.class);
            sqlSessionFactory.setConfiguration(configuration);
            sqlSessionFactory.setTypeAliasesPackage("com.vinjcent.pojo");
            return sqlSessionFactory.getObject();
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • WMybatisConfiguration(写数据源)
    package com.vinjcent.config.mybatis;
    
    import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder;
    import org.apache.ibatis.logging.stdout.StdOutImpl;
    import org.apache.ibatis.session.SqlSessionFactory;
    import org.mybatis.spring.SqlSessionFactoryBean;
    import org.mybatis.spring.annotation.MapperScan;
    import org.springframework.beans.factory.annotation.Qualifier;
    import org.springframework.boot.context.properties.ConfigurationProperties;
    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 javax.sql.DataSource;
    
    
    /**
     * 写数据源配置
     * 1. 指定扫描mapper接口包
     * 2. 指定使用wSqlSessionFactory是哪个
     */
    @Configuration
    @MapperScan(basePackages = "com.vinjcent.mapper.write", sqlSessionFactoryRef = "wSqlSessionFactory")
    public class WMybatisConfiguration {
    
    
        @Bean(name = "writeDatasource")
        @ConfigurationProperties(prefix = "spring.datasource.write")
        public DataSource writeDatasource() {
            // 底层会自动拿到spring.datasource中的配置,创建一个DruidDataSource
            return DruidDataSourceBuilder.create().build();
        }
    
        @Bean
        @Primary
        public SqlSessionFactory wSqlSessionFactory(@Qualifier("writeDatasource") DataSource dataSource) throws Exception {
            final SqlSessionFactoryBean sqlSessionFactory = new SqlSessionFactoryBean();
            sqlSessionFactory.setDataSource(dataSource);
            sqlSessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver()
                    .getResources("classpath:com/vinjcent/mapper/write/*.xml"));
            /* 主库设置sql控制台打印 */
            org.apache.ibatis.session.Configuration configuration = new org.apache.ibatis.session.Configuration();
            configuration.setLogImpl(StdOutImpl.class);
            sqlSessionFactory.setConfiguration(configuration);
            sqlSessionFactory.setTypeAliasesPackage("com.vinjcent.pojo");
            return sqlSessionFactory.getObject();
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    1. 读写mapper接口以及对应映射文件.xml
    • RPeopleMapper
    package com.vinjcent.mapper.read;
    
    import com.vinjcent.pojo.People;
    import org.apache.ibatis.annotations.Mapper;
    
    import java.util.List;
    
    @Mapper
    public interface RPeopleMapper {
    
        List<People> list();
    
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    
    DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
    <mapper namespace="com.vinjcent.mapper.read.RPeopleMapper">
    
        <select id="list" resultType="People">
            select * from `people`
        select>
    mapper>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • WPeopleMapper
    package com.vinjcent.mapper.write;
    
    import com.vinjcent.pojo.People;
    import org.apache.ibatis.annotations.Mapper;
    
    import java.util.List;
    
    @Mapper
    public interface WPeopleMapper {
    
        boolean save(People people);
    
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    
    DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
    <mapper namespace="com.vinjcent.mapper.write.WPeopleMapper">
    
    
        <insert id="save">
            insert into `people`(name)
            values (#{name});
        insert>
    
    mapper>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    1. Service层
      • PeopleServiceImpl
    package com.vinjcent.service.impl;
    
    import com.vinjcent.mapper.read.RPeopleMapper;
    import com.vinjcent.mapper.write.WPeopleMapper;
    import com.vinjcent.pojo.People;
    import com.vinjcent.service.PeopleService;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Service;
    
    import java.util.List;
    
    @Service
    public class PeopleServiceImpl implements PeopleService {
    
        private final WPeopleMapper wPeopleMapper;
    
        private final RPeopleMapper rPeopleMapper;
    
        @Autowired
        public PeopleController(WPeopleMapper wPeopleMapper, RPeopleMapper rPeopleMapper) {
            this.wPeopleMapper = wPeopleMapper;
            this.rPeopleMapper = rPeopleMapper;
        }
    
    	// 读
        @GetMapping("/list")
        public List<People> getAllPeople() {
            return rPeopleMapper.list();
        }
    
        // 写
        @GetMapping("/insert")
        public String addPeople() {
            wPeopleMapper.save(new People("vinjcent"));
            return "添加成功";
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    1. 测试接口
    • PeopleController
    package com.vinjcent.controller;
    
    import com.vinjcent.mapper.read.RPeopleMapper;
    import com.vinjcent.mapper.write.WPeopleMapper;
    import com.vinjcent.pojo.People;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.web.bind.annotation.GetMapping;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RestController;
    
    import java.util.List;
    
    @RestController
    @RequestMapping("people")
    public class PeopleController {
    
        private final PeopleService peopleService;
    
        @Autowired
        public PeopleController(PeopleService peopleService) {
            this.peopleService = peopleService;
        }
    
    
        @GetMapping("/list")
        public List<People> getAllPeople() {
            return peopleService.list();
        }
    
        @GetMapping("/insert")
        public String addPeople() {
            peopleService.save(new People("vinjcent"));
            return "添加成功";
        }
    
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    1. 运行并测试接口

    下一篇文章SpringBoot实现多数据源(五)【多数据源事务控制】

  • 相关阅读:
    微服务开发面试题,java服务端面试题
    Java InputStream.reset()方法具有什么功能呢?
    从阿里出发看微服务发展!P8架构师手打800页微服务深度解析笔记
    2023年第二十届中国研究生数学建模竞赛总结与分享
    CSS学习(1)-选择器
    c++ | makefile | 编译 | 链接库
    webpack常用配置与性能优化插件
    浏览器从输入url到渲染页面发生了什么?
    【开源】新生报到网站 JAVA+Vue.js+SpringBoot+MySQL
    Linux:按时间批量删除文件(删除N天前文件)
  • 原文地址:https://blog.csdn.net/Wei_Naijia/article/details/128069791