SpringBoot项目集成Mybatis Plus(一)多数据源配置

随着微服务使用越来越广泛,功能越做越大,需要支持的数据源也会越来越多,这时就可以在项目中集成Mybatis Plus,支持多数据源。Mybatis Plus在 Mybatis基础上进行了功能扩充,非常方便使用。官方网址为https://mp.baomidou.com/

1、创建Springboot项目,添加maven依赖。

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>dynamic-datasource-spring-boot-starter</artifactId>
    <version>3.2.0</version>
</dependency>
<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus-boot-starter</artifactId>
    <version>3.1.1</version>
</dependency>
<dependency>
    <groupId>Mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <scope>runtime</scope>
</dependency>
<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <version>${lombok.version}</version>
</dependency>

2、多数据源配置

server:
  port: 8090

spring:
  datasource:
    dynamic:
      primary: db1
      hikari:
        minIdle: 5 # 最小空闲链接数
        maxPoolSize: 5 # 最大链接数
        maxLifetime: 180000 # 最大生命周期
        idleTimeout: 60000 # 最长闲置时间
        connectionTimeout: 20000 # 等待连接池的最大毫秒数
      datasource:
        db1:
          url: jdbc:mysql://localhost:3306/poi?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=CONVERT_TO_NULL&useSSL=true&serverTimezone=GMT%2B8
          username: root
          password: root
          driverClassName: com.mysql.cj.jdbc.Driver
        db2:
          url: jdbc:mysql://localhost:3307/wms?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=CONVERT_TO_NULL&useSSL=true&serverTimezone=GMT%2B8
          username: root
          password: root
          driverClassName: com.mysql.cj.jdbc.Driver

mybatis-plus:
  mapper-locations: classpath:/mapper/*.xml
  type-aliases-package: com.demo.mybatisplus.demo.*.entity
  configuration:
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl

3、启动项目。

启动项目,报错:

Failed to configure a DataSource: 'url' attribute is not specified and no embedded datasource could be configured.

Reason: Failed to determine a suitable driver class

需要在启动类的注解里排除掉自动配置类。

@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class})

猜你喜欢

转载自blog.csdn.net/suoyx/article/details/113769828