首页 > 数据库 >springboot+mybatisplus+dynicDatasource 从数据库表中查询数据源 动态添加

springboot+mybatisplus+dynicDatasource 从数据库表中查询数据源 动态添加

时间:2024-04-25 16:47:43浏览次数:27  
标签:dynicDatasource mybatisplus 数据源 AppVersion import com id tenant

1、pom依赖

  <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.7.12</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
 <dependencies>
        <!-- Spring Boot Starter Web -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>


        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
            <version>8.0.33</version>
        </dependency>


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


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

        <!-- 可选:如果使用Lombok提高代码简洁性 -->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
    </dependencies>

2、配置文件

spring:
  datasource:
    dynamic:
      #设置默认的数据源或者数据源组,默认值即为master
      primary: master
      #严格匹配数据源,默认false. true未匹配到指定数据源时抛异常,false使用默认数据源
      strict: false
      datasource:
        master:
          url: jdbc:mysql://127.0.0.1:3306/tenant?serverTimezone=UTC&useUnicode=true&characterEncoding=UTF8&useSSL=false
          username: root
          password: 123456
          driver-class-name: com.mysql.cj.jdbc.Driver

mybatis-plus:
  # ????
  global-config:
    db-config:
      # ????????mysql/oracle/h2/postgresql?
      db-type: mysql
      # ???????not_null/commented/underline_to_camel/to_lowercase?
      field-strategy: not_null
      # ??????????
      capital-mode: true
      # ????????
      column-underline: true
      # ???
      table-prefix:
      # ID?????id_WORKER/AUTO
      id-type: auto
      # SQL???
      logic-delete-value: 1
      logic-not-delete-value: 0
      logic-delete-field: deleted
  mapper-locations: classpath:/mapper/*.xml
  type-aliases-package: com.example.mulittenantdemo.domain
  configuration:
    map-underscore-to-camel-case: true
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl


server:
  port: 8083

3、应用启动的时候动态添加数据源

package com.example.mulittenantdemo.util;

import com.baomidou.dynamic.datasource.DynamicRoutingDataSource;
import com.baomidou.dynamic.datasource.creator.DataSourceProperty;
import com.baomidou.dynamic.datasource.creator.DefaultDataSourceCreator;
import com.example.mulittenantdemo.domain.Tenant;
import com.example.mulittenantdemo.service.TenantService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.sql.DataSource;
import java.util.List;

@Component
public class MyDomic{
    @Autowired
    private DataSource dataSource;
    @Autowired
    private DefaultDataSourceCreator dataSourceCreator;

    @Autowired
    TenantService tenantService;
    @Autowired
    public void init(){

        List<Tenant> list = tenantService.list();
        for (Tenant tenant : list) {
            DataSourceProperty dataSourceProperty = new DataSourceProperty();
            dataSourceProperty.setUrl("jdbc:mysql://127.0.0.1:3306/"+tenant.getDb()+"?serverTimezone=UTC&useUnicode=true&characterEncoding=UTF8&useSSL=false");
            dataSourceProperty.setUsername(tenant.getUser());
            dataSourceProperty.setPassword(tenant.getPwd());
            dataSourceProperty.setDriverClassName("com.mysql.cj.jdbc.Driver");

            DynamicRoutingDataSource ds = (DynamicRoutingDataSource) dataSource;
            DataSource dataSource = dataSourceCreator.createDataSource(dataSourceProperty);
            ds.addDataSource(tenant.getCode(), dataSource);
        }


    }
}

4、动态切换数据源

package com.example.mulittenantdemo.service.impl;

import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.mulittenantdemo.domain.AppVersion;
import com.example.mulittenantdemo.mapper.AppVersionMapper;
import com.example.mulittenantdemo.service.AppVersionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import  com.baomidou.dynamic.datasource.toolkit.DynamicDataSourceContextHolder;



/**
 * @author 许贵林
 * @description 针对表【app_version(app版本管理)】的数据库操作Service实现
 * @createDate 2024-03-19 09:32:09
 */
@Service
public class AppVersionServiceImpl extends ServiceImpl<AppVersionMapper, AppVersion>
        implements AppVersionService {

    @Autowired
    private AppVersionMapper appVersionMapper;

    @Override
    public AppVersion queryById1(Long id) {
        DynamicDataSourceContextHolder.push("slave_1");
        return appVersionMapper.selectById(id);
    }

    @Override
    @DS("slave_2")
    public AppVersion queryById2(Long id) {

        return appVersionMapper.selectById(id);
    }

    @Override

    public AppVersion queryById3(Long id,String code) {
        DynamicDataSourceContextHolder.push(code);
        return appVersionMapper.selectById(id);
    }

    @Override
    @DS("primary")
    public AppVersion queryById(Long id) {

        return appVersionMapper.myqueryById111(id);
    }
}
public interface AppVersionService extends IService<AppVersion> {

    AppVersion queryById(Long id);
    AppVersion queryById1(Long id);

    AppVersion queryById2(Long id);

    AppVersion queryById3(Long id,String code);
}
    @GetMapping("/get3/{id}/{code}")
    public AppVersion sayHello3(@PathVariable("id") Long id,@PathVariable("code") String code) {
        AppVersion byId = appVersionService.queryById3(id,code);
        System.out.println(byId);
        return (byId);
    }

 租户库:tenant 表设计

CREATE TABLE `t_tenant`  (
  `id` bigint(20) NOT NULL AUTO_INCREMENT,
  `code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL COMMENT '租户编码',
  `db` varchar(500) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL,
  `user` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL,
  `pwd` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL,
  PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 4 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_unicode_ci ROW_FORMAT = Dynamic;

-- ----------------------------
-- Records of t_tenant
-- ----------------------------
INSERT INTO `t_tenant` VALUES (1, 'farm', 'farm', 'root', '123456');
INSERT INTO `t_tenant` VALUES (2, 'from1', 'from1', 'root', '123456');
INSERT INTO `t_tenant` VALUES (3, 'farm2', 'farm2', 'root', '123456');

 

标签:dynicDatasource,mybatisplus,数据源,AppVersion,import,com,id,tenant
From: https://www.cnblogs.com/niun/p/18158007

相关文章

  • Navicat连接SQL server出现:[IM002] [Microsoft][ODBC 驱动程序管理器] 未发现数据源名
    问题 解决方法一找到Navicat的安装路径,然后找到sqlncli_x64.msi文件并安装,安装成功后重启Navicat重新进行连接,看是否成功。 解决方法二如果方法一没有找到找到sqlncli_x64.msi还是Navicat的安装路径,然后找到msodbcsql_64.msi文件并安装,安装成功后重启Navicat重新进行连接......
  • mybatisplus分页中,模糊匹配一个字符串在列a或者列b下都可以筛选出的写法
    话不多说,直接上代码,and那句就对了LambdaQueryWrapper<类>wrapper=newLambdaQueryWrapper<类>().in(逻辑内容).like(正常逻辑内容).and(wrapperNew->wrapperNew.like(StringUtils.isNotEmpty(filter.getLocation()),......
  • 自动生成数据库设计文档,支持多数据源批量生成(Word文档)
       在做项目时通常使用PowerDesigner设计数据库,但在项目完成交付项目给客户的时候常常需要一份Word版本的数据库文档给客户,你不能指望每个客户都会用PowerDesigner,所以基于当前开发数据库生成数据库文档就是最佳选择,如果手动编写数据库文档那将是一件非常痛苦的费力不讨好的......
  • 【SpringBoot】【一】初识数据源连接池
    1 前言上节我们看了看,SpringBoot启动后都有哪些线程,看到有一部分是关于数据源连接池的,那么这节我们就看看数据源连接池都是如何工作的。我们本节就从这两个问题看起:(1)连接池是如何创建的,也就是什么时候创建的呢?(2)连接是什么时候放进连接池的?是创建完就初始化了一批新的连接,还......
  • ETLCloud中数据源使用和管理的技巧
    ETL中数据源管理的重要性在现代企业信息化进程中,数据已成为驱动决策、优化运营、提升竞争力的关键要素。而作为数据处理与分析的重要环节,ETL(Extract, Transform, Load)过程承担着从多种异构数据源中抽取数据,进行必要的转换,并将其加载到目标系统(如数据仓库或数据湖)中的重任。其中......
  • springBoot 多数据源配置
    常规数据源#应用端口server:port:5555spring:datasource:username:rootpassword:ffjy1101url:jdbc:mysql://localhost:3306/mybatis?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8&useSSL=falsedriver-class-name:com.......
  • mybatisplus常用写法
    一、QueryWrapper和LambdaQueryWrapper的区别写法和表达方式不同:QueryWrapper:使用传统的字符串形式构建查询条件,通过支持链式调用的方式,可以方便地拼接多个查询条件。LambdaQueryWrapper:使用Lambda表达式构建查询条件,可以通过实体类的属性和方法来安全地编写查询条件,减少犯......
  • mybatisplus
    官网啥都有https://baomidou.com/1.引入依赖<dependency><groupId>com.baomidou</groupId><artifactId>mybatis-plus-boot-starter</artifactId><version>3.5.3.1</version></dependency>2.定义Mapp......
  • mybatisplus
    mybatisplus如何实现获取信息通过扫描实体类并通过反射获取实体类信息作为数据库表信息约定:类名、变量名驼峰转下划线作为表名id字段默认为主键常用注解@TableName,@TableId,@TableField@TableField使用场景:成员变量为boolean并且名称为is开头,转化时会去掉is......
  • 80、SpringBoot3 SpringSecurity Mybatisplus最新版 整合 实现登入权限控制
    1、导入pom依赖<?xmlversion="1.0"encoding="UTF-8"?><projectxmlns="http://maven.apache.org/POM/4.0.0"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apac......