目录

MyBatisPlus 多数据源配置

目录

[一、mybatis-plus 简介](#一、mybatis-plus 简介)

特性

二、支持数据库:

[三、 开发实例](#三、 开发实例)

[1. 引入依赖:](#1. 引入依赖:)

[2. 参数配置application.yml](#2. 参数配置application.yml)

[3. 在 Spring Boot 启动类中添加 @MapperScan 注解,扫描 Mapper 文件夹:](#3. 在 Spring Boot 启动类中添加 @MapperScan 注解,扫描 Mapper 文件夹:)

[4. 编写实体类 User.java(此处使用了 Lombok (opens new window)简化代码)](#4. 编写实体类 User.java(此处使用了 Lombok (opens new window)简化代码))

[5. 编写 Mapper 包下的 UserMapper接口](#5. 编写 Mapper 包下的 UserMapper接口)

[6. 测试](#6. 测试)

[四、 多数据源](#四、 多数据源)

[1. 约定](#1. 约定)

[2. 配置数据源](#2. 配置数据源)

[3. 使用 @DS 切换数据源](#3. 使用 @DS 切换数据源)


一、mybatis-plus 简介

mybatis-plus 是一个 Mybatis 的增强工具,在 Mybatis 的基础上只做增强不做改变,为简化开发、提高效率而生。这是官方给的定义,关于mybatis-plus的更多介绍及特性,可以参考MyBatis-Plus官网

特性

  • 无侵入:只做增强不做改变,引入它不会对现有工程产生影响,如丝般顺滑
  • 损耗小:启动即会自动注入基本 CURD,性能基本无损耗,直接面向对象操作
  • 强大的 CRUD 操作:内置通用 Mapper、通用 Service,仅仅通过少量配置即可实现单表大部分 CRUD 操作,更有强大的条件构造器,满足各类使用需求
  • 支持 Lambda 形式调用:通过 Lambda 表达式,方便的编写各类查询条件,无需再担心字段写错
  • 支持主键自动生成:支持多达 4 种主键策略(内含分布式唯一 ID 生成器 - Sequence),可自由配置,完美解决主键问题
  • 支持 ActiveRecord 模式:支持 ActiveRecord 形式调用,实体类只需继承 Model 类即可进行强大的 CRUD 操作
  • 支持自定义全局通用操作:支持全局通用方法注入( Write once, use anywhere )
  • 内置代码生成器:采用代码或者 Maven 插件可快速生成 Mapper 、 Model 、 Service 、 Controller 层代码,支持模板引擎,更有超多自定义配置等您来使用
  • 内置分页插件:基于 MyBatis 物理分页,开发者无需关心具体操作,配置好插件之后,写分页等同于普通 List 查询
  • 分页插件支持多种数据库:支持 MySQL、MariaDB、Oracle、DB2、H2、HSQL、SQLite、Postgre、SQLServer 等多种数据库
  • 内置性能分析插件:可输出 SQL 语句以及其执行时间,建议开发测试时启用该功能,能快速揪出慢查询
  • 内置全局拦截插件:提供全表 delete 、 update 操作智能分析阻断,也可自定义拦截规则,预防误操作

二、支持数据库:

MySQL,Oracle,DB2,H2,HSQL,SQLite,PostgreSQL,SQLServer,Phoenix,Gauss ,ClickHouse,Sybase,OceanBase,Firebird,Cubrid,Goldilocks,csiidb

三、 开发实例

1. 引入依赖:

复制代码
<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>com.baomidou</groupId>
        <artifactId>mybatis-plus-boot-starter</artifactId>
        <version>最新版本</version>
    </dependency>
    <dependency>
        <groupId>com.h2database</groupId>
        <artifactId>h2</artifactId>
        <scope>runtime</scope>
    </dependency>
</dependencies>

2. 参数配置application.yml

复制代码
spring:
  datasource:
    driver-class-name: org.h2.Driver
    schema: classpath:db/schema-h2.sql
    username: root
    password: test
  sql:
    init:
      schema-locations: classpath:db/schema-h2.sql
      data-locations: classpath:db/data-h2.sql

3. 在 Spring Boot 启动类中添加 @MapperScan 注解,扫描 Mapper 文件夹:

复制代码
@SpringBootApplication
@MapperScan("com.baomidou.mybatisplus.samples.quickstart.mapper")
public class Application {

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

}

4. 编写实体类 User.java(此处使用了 Lombok (opens new window)简化代码)

复制代码
@Data
public class User {
    private Long id;
    private String name;
    private Integer age;
    private String email;
}

5. 编写 Mapper 包下的 UserMapper接口

复制代码
public interface UserMapper extends BaseMapper<User> {

}

6. 测试

复制代码
 @Autowired
    private UserMapper userMapper;

    @Test
    public void testSelect() {
        System.out.println(("----- selectAll method test ------"));
        List<User> userList = userMapper.selectList(null);
        Assert.assertEquals(5, userList.size());
        userList.forEach(System.out::println);
    }

四、 多数据源

1. 约定

  1. 本框架只做 切换数据源 这件核心的事情,并不限制你的具体操作,切换了数据源可以做任何CRUD。

2.配置文件所有以下划线 _ 分割的数据源 首部 即为组的名称,相同组名称的数据源会放在一个组下。

  1. 切换数据源可以是组名,也可以是具体数据源名称。组名则切换时采用负载均衡算法切换。

  2. 默认的数据源名称为 master ,你可以通过 spring.datasource.dynamic.primary 修改。

  3. 方法上的注解优先于类上注解。

  4. DS支持继承抽象类上的DS,暂不支持继承接口上的DS。

2. 使用方法

  1. 引入dynamic-datasource-spring-boot-starter。

    <dependency> <groupId>com.baomidou</groupId> <artifactId>dynamic-datasource-spring-boot-starter</artifactId> <version>${version}</version> </dependency>

2. 配置数据源

复制代码
spring:
  datasource:
    dynamic:
      primary: master #设置默认的数据源或者数据源组,默认值即为master
      strict: false #严格匹配数据源,默认false. true未匹配到指定数据源时抛异常,false使用默认数据源
      datasource:
        master:
          url: jdbc:mysql://xx.xx.xx.xx:3306/dynamic
          username: root
          password: 123456
          driver-class-name: com.mysql.jdbc.Driver # 3.2.0开始支持SPI可省略此配置
        slave_1:
          url: jdbc:mysql://xx.xx.xx.xx:3307/dynamic
          username: root
          password: 123456
          driver-class-name: com.mysql.jdbc.Driver
        slave_2:
          url: ENC(xxxxx) # 内置加密,使用请查看详细文档
          username: ENC(xxxxx)
          password: ENC(xxxxx)
          driver-class-name: com.mysql.jdbc.Driver
       #......省略
       #以上会配置一个默认库master,一个组slave下有两个子库slave_1,slave_2

3. 使用 @DS 切换数据源

复制代码
@Service
@DS("slave")
public class UserServiceImpl implements UserService {

  @Autowired
  private JdbcTemplate jdbcTemplate;

  public List selectAll() {
    return  jdbcTemplate.queryForList("select * from user");
  }
  
  @Override
  @DS("slave_1")
  public List selectByCondition() {
    return  jdbcTemplate.queryForList("select * from user where age >10");
  }
}
本文是转载文章,点击查看原文
如有侵权,请联系 xyy@jishuzhan.net 删除
相关推荐
eternal__day4 分钟前
第二期:[特殊字符] 深入理解MyBatis[特殊字符]MyBatis基础CRUD操作详解[特殊字符]
java·spring·java-ee·maven·mybatis
魔道不误砍柴功34 分钟前
SpringCloud Alibaba 之分布式全局事务 Seata 原理分析
分布式·spring·spring cloud
图南随笔1 小时前
Spring Boot(二十一):RedisTemplate的String和Hash类型操作
java·spring boot·redis·后端·缓存
麓殇⊙2 小时前
mybatis--多对一处理/一对多处理
java·tomcat·mybatis
Java个体户3 小时前
mybatis 嵌套List
mybatis
阿杆3 小时前
🤯我写了一套无敌的参数校验组件④ | 现已支持 i18n
java·spring
技术宝哥3 小时前
解决 Spring Boot 启动报错:数据源配置引发的启动失败
spring boot·后端·mybatis
码农周4 小时前
Spring Boot 启动后自动执行 Service 方法终极指南
java·spring boot·后端
隔壁小查4 小时前
【后端开发】Spring配置文件
java·spring·microsoft
王有品4 小时前
Spring MVC 全栈指南:RESTful 架构、核心注解与 JSON 实战解析
spring·mvc