【SpringBoot DB 系列】Mybatis-Plus 多数据源配置

124 篇文章 16 订阅
11 篇文章 0 订阅

【SpringBoot DB 系列】Mybatis-Plus 多数据源配置

前面介绍了两种 Mybatis 的数据源配置,当然也少不了 mybatis-plus

MyBatis-Plus (opens new window)(简称 MP)是一个 MyBatis (opens new window)的增强工具,在 MyBatis 的基础上只做增强不做改变,既然做增强,那多数据源这种硬性场景,肯定是有非常简单的解决方案的

本文将实例演示 Mybatis-Plus 多数据源的配置

I. 环境准备

1. 数据库相关

以 mysql 为例进行演示说明,因为需要多数据源,一个最简单的 case 就是一个物理库上多个逻辑库,本文是基于本机的 mysql 进行操作

创建数据库teststory,两个库下都存在一个表money (同名同结构表,但是数据不同哦)

CREATE TABLE `money` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `name` varchar(20) NOT NULL DEFAULT '' COMMENT '用户名',
  `money` int(26) NOT NULL DEFAULT '0' COMMENT '钱',
  `is_deleted` tinyint(1) NOT NULL DEFAULT '0',
  `create_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
  `update_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
  PRIMARY KEY (`id`),
  KEY `name` (`name`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8mb4;

2. 项目环境

本项目借助SpringBoot 2.2.1.RELEASE + maven 3.5.3 + IDEA进行开发

下面是核心的pom.xml(源码可以再文末获取)

<dependencies>
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
    </dependency>

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

    <dependency>
        <groupId>com.baomidou</groupId>
        <artifactId>mybatis-plus-boot-starter</artifactId>
        <version>3.3.1</version>
    </dependency>
</dependencies>

配置文件信息application.yml,请注意下面的写法格式,如有疑问可以参考官方教程

spring:
  datasource:
    dynamic:
      primary: story #设置默认的数据源或者数据源组,默认值即为master
      strict: false  #设置严格模式,默认false不启动. 启动后在未匹配到指定数据源时候会抛出异常,不启动则使用默认数据源.
      datasource:
        story:
          driver-class-name: com.mysql.cj.jdbc.Driver
          url: jdbc:mysql://127.0.0.1:3306/story?useUnicode=true&characterEncoding=UTF-8&useSSL=false&serverTimezone=Asia/Shanghai
          username: root
          password:
        test:
          driver-class-name: com.mysql.cj.jdbc.Driver
          url: jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&characterEncoding=UTF-8&useSSL=false&serverTimezone=Asia/Shanghai
          username: root
          password:

II. 项目演示

本文主要参考自 Mybatis-Plus 官方教程,如后续版本有啥变动,请以官方说明为准
https://mp.baomidou.com/guide/dynamic-datasource.html#%E6%96%87%E6%A1%A3-documentation

1. 实体类

mybatis-plus 可以借助插件实现自动生成相应的代码,我们这里简单自主实现测试 demo,因为两个数据库中表结构完全一致,所以只需要一个 Entity

@Data
@Accessors(chain = true)
@TableName(value = "money")
public class MoneyPo {
    /**
     * 指定自增策略
     */
    @TableId(value = "id", type = IdType.AUTO)
    private Integer id;

    private String name;

    private Long money;

    @TableField("is_deleted")
    private Integer isDeleted;

    @TableField(value = "create_at")
    private Timestamp createAt;

    @TableField(value = "update_at")
    private Timestamp updateAt;
}

2. Mapper 接口

数据库操作定义接口MoneyMapper

public interface MoneyMapper extends BaseMapper<MoneyPo> {
}

对应的 xml 文件resources/mapper/money-mapper.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.git.hui.boot.multi.datasource.mapper.MoneyMapper">
</mapper>

3. Service 接口与实现

因为两张表,所以我们可以定义一个接口,两个不同的实现

public interface MoneyService extends IService<MoneyPo> {
}

@Service
@DS("story")
public class StoryMoneyServiceImpl extends ServiceImpl<MoneyMapper, MoneyPo> implements MoneyService {
}

@Service
@DS("test")
public class TestMoneyServiceImpl extends ServiceImpl<MoneyMapper, MoneyPo> implements MoneyService {
}

请注意上面 Service 的注解@DS,value 为前面数据源配置文件中的 key(spring.datasource.dynamic.datasource下面的story + test)

这个注解可以放在类上也可以放在方法上,方法上的优先级 > 类,所以上面的两个 Service 实现可以改成一个

@Service
public class MoneyServiceImpl extends ServiceImpl<MoneyMapper, MoneyPo> implements MoneyService {

    @DS("story")
    public List<MoneyPo> findByStoryIds(Collection<Long> ids) {
        return baseMapper.selectBatchIds(ids);
    }

    @DS("test")
    public List<MoneyPo> findByTestIds(Collection<Long> ids) {
        return baseMapper.selectBatchIds(ids);
    }
}

4. 测试

为简单起见,直接在启动类中添加写上测试代码

@SpringBootApplication
@MapperScan("com.git.hui.boot.multi.datasource.mapper")
public class Application {

    public Application(TestMoneyServiceImpl testMoneyService, StoryMoneyServiceImpl storyMoneyService) {
        List<MoneyPo> moneyPoList = testMoneyService.listByIds(Arrays.asList(1, 1000));
        System.out.println(moneyPoList);
        System.out.println("--------------");

        moneyPoList = storyMoneyService.listByIds(Arrays.asList(1, 1000));
        System.out.println(moneyPoList);
    }

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

II. 其他

0. 项目

相关博文

源码

1. 一灰灰 Blog

尽信书则不如,以上内容,纯属一家之言,因个人能力有限,难免有疏漏和错误之处,如发现 bug 或者有更好的建议,欢迎批评指正,不吝感激

下面一灰灰的个人博客,记录所有学习和工作中的博文,欢迎大家前去逛逛

一灰灰blog

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
Mybatis-Plus支持多数据源配置,可以通过配置多个数据源来实现在不同的数据库中进行数据操作。具体配置步骤如下: 1. 在application.properties文件中配置多个数据源的连接信息,例如: ``` # 数据源1 spring.datasource.url=jdbc:mysql://localhost:3306/db1?useUnicode=true&characterEncoding=utf-8&useSSL=false spring.datasource.username=root spring.datasource.password=root spring.datasource.driver-class-name=com.mysql.jdbc.Driver # 数据源2 spring.datasource.test2.url=jdbc:mysql://localhost:3306/db2?useUnicode=true&characterEncoding=utf-8&useSSL=false spring.datasource.test2.username=root spring.datasource.test2.password=root spring.datasource.test2.driver-class-name=com.mysql.jdbc.Driver ``` 2. 在Mybatis-Plus配置文件中配置多个SqlSessionFactory,例如: ``` @Configuration public class MybatisPlusConfig { @Bean(name = "test1SqlSessionFactory") public SqlSessionFactory test1SqlSessionFactory(@Qualifier("test1DataSource") DataSource dataSource) throws Exception { MybatisSqlSessionFactoryBean bean = new MybatisSqlSessionFactoryBean(); bean.setDataSource(dataSource); bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath*:mapper/test1/*.xml")); return bean.getObject(); } @Bean(name = "test2SqlSessionFactory") public SqlSessionFactory test2SqlSessionFactory(@Qualifier("test2DataSource") DataSource dataSource) throws Exception { MybatisSqlSessionFactoryBean bean = new MybatisSqlSessionFactoryBean(); bean.setDataSource(dataSource); bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath*:mapper/test2/*.xml")); return bean.getObject(); } } ``` 3. 在Mybatis-Plus配置文件中配置多个MapperScannerConfigurer,例如: ``` @Configuration public class MybatisPlusConfig { @Bean(name = "test1MapperScannerConfigurer") public MapperScannerConfigurer test1MapperScannerConfigurer() { MapperScannerConfigurer configurer = new MapperScannerConfigurer(); configurer.setBasePackage("com.example.mapper.test1"); configurer.setSqlSessionFactoryBeanName("test1SqlSessionFactory"); return configurer; } @Bean(name = "test2MapperScannerConfigurer") public MapperScannerConfigurer test2MapperScannerConfigurer() { MapperScannerConfigurer configurer = new MapperScannerConfigurer(); configurer.setBasePackage("com.example.mapper.test2"); configurer.setSqlSessionFactoryBeanName("test2SqlSessionFactory"); return configurer; } } ``` 4. 在Mapper接口中使用@Mapper注解指定对应的SqlSessionFactory,例如: ``` @Mapper public interface Test1Mapper { // ... } @Mapper public interface Test2Mapper { // ... } ``` 这样就可以在不同的Mapper接口中使用不同的数据源进行数据操作了。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

一灰灰blog

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值