首页 > 其他分享 >springboot mybatis-plus dynamic-datasource实现

springboot mybatis-plus dynamic-datasource实现

时间:2024-04-25 14:12:12浏览次数:19  
标签:springboot dynamic AppVersion Long public plus mysql byId id

基础架构是springboot +mybatis-plus 实现动态数据源步骤

步骤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.1</version>


        </dependency>


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

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

步骤二、springboot配置文件 application.yml

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

步骤3 service

public interface AppVersionService extends IService<AppVersion> {

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

    AppVersion queryById2(Long id);
}

步骤4、serviceImpl

@Service
public class AppVersionServiceImpl extends ServiceImpl<AppVersionMapper, AppVersion>
        implements AppVersionService {

    @Autowired
    private AppVersionMapper appVersionMapper;

    @Override
    @DS("slave_1")
    public AppVersion queryById1(Long id) {

        return appVersionMapper.selectById(id);
    }

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

        return appVersionMapper.selectById(id);
    }

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

        return appVersionMapper.myqueryById111(id);
    }
}

 步骤5、mapper

public interface AppVersionMapper extends BaseMapper<AppVersion> {
    AppVersion myqueryById(Long id);


    @Select("SELECT * FROM app_version WHERE id = #{id}")
    AppVersion myqueryById111(@Param("id") Long id);
}

 步骤6、controller

@RestController
@RequestMapping("/app")
@Validated
public class AppController {
    @Autowired
    private AppVersionService appVersionService;

    @GetMapping("/get/{id}")
    public AppVersion sayHello(@PathVariable("id") Long id) {
        AppVersion byId = appVersionService.queryById(id);
        System.out.println(byId);
        return byId;
    }
    @GetMapping("/get1/{id}")
    public AppVersion sayHello1(@PathVariable("id") Long id) {
        AppVersion byId = appVersionService.queryById1(id);
        System.out.println(byId);
        return byId;
    }

    @GetMapping("/get2/{id}")
    public AppVersion sayHello2(@PathVariable("id") Long id) {
        AppVersion byId = appVersionService.queryById2(id);
        System.out.println(byId);
        return (byId);
    }



}

 

标签:springboot,dynamic,AppVersion,Long,public,plus,mysql,byId,id
From: https://www.cnblogs.com/niun/p/18157606

相关文章

  • SpringBoot项目添加2FA双因素身份认证
    什么是2FA(双因素身份验证)?双因素身份验证(2FA)是一种安全系统,要求用户提供两种不同的身份验证方式才能访问某个系统或服务。国内普遍做短信验证码这种的用的比较少,不过在国外的网站中使用双因素身份验证的还是很多的。用户通过使用验证器扫描二维码,就能在app上获取登录的动态口令,......
  • MyBatis Plus 按指定顺序查询对象列表
    场景定义了一个字段,存储了一个json数组比如:[41,38,42],它的含义是一个线性的流程定义,所以保证顺序至关重要现在使用MyBatisPlus的API方法去通过ID数组查询得到对象数组List<ProcessNodePO>processNodeList=processNodeMapper.selectList(newLambdaQueryWrapper<Pro......
  • SpringBoot项目实现日志打印SQL明细(包括SQL语句和参数)几种方式
    前言我们在开发项目的时候,都会连接数据库。有时候遇到问题需要根据我们编写的SQL进行分析,但如果不进行一些开发或者配置的话,这些SQL是不会打印到控制台的,它们默认是隐藏的。下面给大家介绍几种常用的方法。第一种、代码形式Mybatis框架是Java程序员最常用的数据库映射框架,MyBa......
  • 9.prometheus监控--监控springboot2.x(Java)
    一、环境部署yumsearchjava|grepjdkyuminstall-yjava-11-openjdk-devel二、监控java应用(tomcat/jar)JMXexporter负责收集Java虚拟机信息---没举例,等以后再做测试进入到tomcat安装目录,vimPROMETHEUS_JMX_EXPORTER_OPTS="-javaagent:../prometheus-exporter......
  • springboot的netty代码实操
    参考:https://www.cnblogs.com/mc-74120/p/13622008.htmlpom文件<dependency><groupId>io.netty</groupId><artifactId>netty-all</artifactId></dependency>启动类@EnableFeignClients@EnableDiscoveryClient@EnableSchedu......
  • Mybatis Plus使用QueryWrapper、EntityWrapper配置Or的查询方法
    QueryWrapper↓↓↓↓构建代码QueryWrapper<UserPharmacy>wrapper=newQueryWrapper<UserPharmacy>();           wrapper.eq("a.delType",0)                   .and(StrUtil.isNotBlank(userPharmacyQueryDTO.getName()),wrapper1->wrapp......
  • sqlplus 下 常用设置
    OS:RedHatEnterpriseLinuxServerrelease6.3(Santiago)DB:11.2.0.4.0设置行的宽度和页的行数SQL>setline233pages233显示sql执行的时间SQL>settimingonSQL>selectinstance_namefromv$instance;INSTANCE_NAME----------------PRDElapsed:00......
  • [Vue3+Element-Plus]点击列表中的图片预览时,图片被表格覆盖
    preview-teleported="true" <el-table-columnprop="id"label="ID"width="80"align="center"sortable/><el-table-columnlabel="商品图片"width="85px"><template#default=&q......
  • springboot 结合jackson数据脱敏
     在返回字段时有时需要对电话,地址等字段进行脱敏处理1.定义枚举脱敏类使用函数编程,绑定函数操作publicenumDataMaskEnum{/***名称脱敏*/USERNAME(s->s.replaceAll("(\\S)\\S(\\S*)","$1*$2")),/***手机号脱敏*/......
  • springboot源码:容器启动过程(扩展业务对象、bean 生命周期)&动态注册自己的业务对象&
    0.SpringbootRun方法启动org.springframework.boot.SpringApplication#run(java.lang.String...)启动 publicConfigurableApplicationContextrun(String...args){ longstartTime=System.nanoTime(); DefaultBootstrapContextbootstrapContext=createBootstrap......