springboot+mybatisplus使用注解多数据源整合

迷南。 2022-12-26 15:22 232阅读 0赞

1.主要依赖包

  1. <dependency>
  2. <groupId>com.baomidou</groupId>
  3. <artifactId>mybatis-plus-generator</artifactId>
  4. <version>3.3.2</version>
  5. </dependency>
  6. <dependency>
  7. <groupId>com.baomidou</groupId>
  8. <artifactId>mybatis-plus-boot-starter</artifactId>
  9. <version>3.3.2</version>
  10. </dependency>
  11. <dependency>
  12. <groupId>com.baomidou</groupId>
  13. <artifactId>dynamic-datasource-spring-boot-starter</artifactId>
  14. <version>3.1.0</version>
  15. </dependency>
  16. <dependency>
  17. <groupId>mysql</groupId>
  18. <artifactId>mysql-connector-java</artifactId>
  19. <scope>runtime</scope>
  20. </dependency>

2.application.yml 配置文件

  1. server:
  2. port: 8080
  3. spring:
  4. datasource:
  5. dynamic:
  6. primary: db1 # 配置默认数据库
  7. datasource:
  8. db1: # 数据源1配置
  9. url: jdbc:mysql://localhost:3306/db1?characterEncoding=utf8&useUnicode=true&useSSL=false&serverTimezone=GMT%2B8
  10. username: root
  11. password: root
  12. driver-class-name: com.mysql.cj.jdbc.Driver
  13. db2: # 数据源2配置
  14. url: jdbc:mysql://localhost:3306/db2?characterEncoding=utf8&useUnicode=true&useSSL=false&serverTimezone=GMT%2B8
  15. username: root
  16. password: root
  17. driver-class-name: com.mysql.cj.jdbc.Driver
  • DruidDataSourceAutoConfigure会注入一个DataSourceWrapper,其会在原生的spring.datasource下找 url, username, password 等。动态数据源 URL 等配置是在 dynamic 下,因此需要排除,否则会报错。排除方式有两种,一种是上述配置文件排除,还有一种可以在项目启动类排除:

    @SpringBootApplication(exclude = DruidDataSourceAutoConfigure.class)
    public class Application {
    public static void main(String[] args) {

    1. SpringApplication.run(Application.class, args);

    }
    }

给使用非默认数据源添加注解@DS

@DS 可以注解在方法上和类上,同时存在方法注解优先于类上注解。
注解在 service 实现或 mapper 接口方法上,不要同时在 service 和 mapper 注解。

  1. @DS("db1")
  2. public interface UserMapper extends BaseMapper<User> {
  3. }
  4. @Service
  5. @DS("db2")
  6. public class ModelServiceImpl extends ServiceImpl<ModelMapper, Model> implements IModelService {}
  7. @Select("SELECT * FROM user")
  8. @DS("db2")
  9. List<User> selectAll();

发表评论

表情:
评论列表 (有 0 条评论,232人围观)

还没有评论,来说两句吧...

相关阅读

    相关 springboot整合数据

    在项目开发中,尤其是在分布式项目中,数据源分布在不同的数据库是常有的事,在项目搭建之初,如果能够想到这个问题,提前规划好相应的项目结构,可以给后面的开发和维护省去很多麻烦;