添加链接
link管理
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接
com.baomidou dynamic-datasource-spring-boot-starter 3.2.1 com.baomidou mybatis-plus-boot-starter 3.4.1 mysql mysql-connector-java 8.0.22 com.alibaba druid-spring-boot-starter 1.2.3 com.baomidou mybatis-plus-generator 3.4.1 compile true org.apache.velocity velocity-engine-core 2.2 compile true org.freemarker freemarker 2.3.30 compile true

配置文件application.yml

spring:
  autoconfigure:
    #自动化配置 例外处理
    exclude: com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceAutoConfigure
  # dynamic-datasource-spring-boot-starter 动态数据源的配置内容
  datasource:
    type: com.alibaba.druid.pool.DruidDataSource
    dynamic:
      primary: test # 设置默认的数据源或者数据源组,默认值即为 master
      datasource:
        # test 数据源配置
        test:
          url: jdbc:mysql://192.168.1.120:3306/db_test?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC
          driver-class-name: com.mysql.cj.jdbc.Driver
          username: root
          password: root1234
        # test1 数据源配置
        test1:
          url: jdbc:mysql://192.168.1.120:3306/db_test1?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC
          driver-class-name: com.mysql.cj.jdbc.Driver
          username: root
          password: root1234
        # test2 数据源配置
        test2:
          url: jdbc:mysql://192.168.1.120:3306/db_test2?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC
          driver-class-name: com.mysql.cj.jdbc.Driver
          username: root
          password: root1234
      #dynamic - 公共配置
      druid:
        initialSize: 5
        minIdle: 5
        maxActive: 30
        maxWait: 60000
        timeBetweenEvictionRunsMillis: 60000
        minEvictableIdleTimeMillis: 300000
        validationQuery: SELECT 'x'
        testWhileIdle: true
        testOnBorrow: false
        testOnReturn: false
        poolPreparedStatements: true
        maxPoolPreparedStatementPerConnectionSize: 20
        filters: stat,wall,slf4j,config
        useGlobalDataSourceStat: true
        stat:
          log-slow-sql: true
          merge-sql: true
          slow-sql-millis: 10000
mybatis-plus:
  type-aliases-package: com.*
  mapper-locations: classpath*:mapper/*.xml

如果没有设置上文红色部分配置,请在启动类的 SpringBootApplication 注解上加入过滤配置:

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

不加过滤的话,SpringBoo t会自动检测到启动了database模块,会去配置文件中druid下面找url,找不到就会报如下问题:

Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dataSource' defined in class path resource [com/alibaba/druid/spring/boot/autoconfigure/DruidDataSourceAutoConfigure.class]: Invocation of init method failed; nested exception is org.springframework.boot.autoconfigure.jdbc.DataSourceProperties$DataSourceBeanCreationException: Failed to determine a suitable driver class
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1778)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:593)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:515)
    at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:320)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:318)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199)
    at org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:277)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.addCandidateEntry(DefaultListableBeanFactory.java:1467)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.findAutowireCandidates(DefaultListableBeanFactory.java:1431)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveMultipleBeans(DefaultListableBeanFactory.java:1350)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1209)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1171)
    at org.springframework.beans.factory.support.ConstructorResolver.resolveAutowiredArgument(ConstructorResolver.java:857)
    at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:760)
    ... 117 common frames omitted
Caused by: org.springframework.boot.autoconfigure.jdbc.DataSourceProperties$DataSourceBeanCreationException: Failed to determine a suitable driver class
    at org.springframework.boot.autoconfigure.jdbc.DataSourceProperties.determineDriverClassName(DataSourceProperties.java:233)
    at org.springframework.boot.autoconfigure.jdbc.DataSourceProperties.determineUsername(DataSourceProperties.java:327)
    at com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceWrapper.afterPropertiesSet(DruidDataSourceWrapper.java:40)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1837)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1774)
    ... 131 common frames omitted
2020-11-19 15:34:16.885[main]|INFO|org.eclipse.jetty.server.handler.ContextHandler - Stopped o.s.b.w.e.j.JettyEmbeddedWebAppContext@455d04d2{application,/,[file:///C:/Users/Administrator.USER-20190109GW/AppData/Local/Temp/jetty-docbase.2008797717949458032.12394/, jar:file:/D:/Server/maven/repository/io/springfox/springfox-swagger-ui/2.9.2/springfox-swagger-ui-2.9.2.jar!/META-INF/resources],UNAVAILABLE}
2020-11-19 15:34:16.886[main]|WARN|o.s.b.w.s.c.AnnotationConfigServletWebServerApplicationContext - Exception encountered during context initialization - cancelling refresh attempt: org.springframework.context.ApplicationContextException: Unable to start web server; nested exception is org.springframework.boot.web.server.WebServerException: Unable to start embedded Jetty web server
2020-11-19 15:34:16.901[main]|INFO|o.s.b.a.l.ConditionEvaluationReportLoggingListener - 
Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2020-11-19 15:34:16.905[main]|ERROR|o.s.b.diagnostics.LoggingFailureAnalysisReporter - 
***************************
APPLICATION FAILED TO START
***************************
Description:
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
Action:
Consider the following:
    If you want an embedded database (H2, HSQL or Derby), please put it on the classpath.
    If you have database settings to be loaded from a particular profile you may need to activate it (no profiles are currently active).
Disconnected from the target VM, address: '127.0.0.1:14992', transport: 'socket'
Process finished with exit code 1

用法:在service实现层 或者 方法上 添加注解@DS("你的db key"),选定数据源,如:

@DS("test")
@Service("userService")
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

mybatis plus + druid多数据源(使用dynamic实现)

Springboot mybatis plus druid多数据源解决方案 dynamic-datasource的使用

https://gitee.com/hejr.cn.com/SpringBoot2.0_2019/blob/master/springboot2_004/pom.xml

https://github.com/baomidou/dynamic-datasource-spring-boot-starter/blob/master/pom.xml

之前一篇讲了vue2.0的框架搭建,本篇主要讲后台使用springboot+mybatisplus. 在springboot项目中引入mybatisplus,需要在pom.xml加入 <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> <version>3.4.1</version
<properties> <dynamic-datasource.version>3.2.1</dynamic-datasource.version> <mybatis-plus.version>3.4.2</mybatis-plus.version> <druid.version>1.2.4</druid.version> </properties> <dependen
最近项目的数据库有单表数据已经超过2千w了,开始进行用mycat分表,就需要把之前的数据重新导入mycat逻辑表中,按着有分表规则依次分散到不同的分表当中。我的操作是部署一个mycat服务并配置好一系列的分表配置,写一个多数据源程序,从原始的数据库链接中读取数据再插入mycat的链接中 参考 mycat 多数据源官方文档 1.application.yml配置文件 spring: datasource: type: com.zaxxer.hikari.HikariDataSource <dependency> <groupId>com.alibaba</groupId> <artifactId>druid-spring-boot-starter</artifactId> <version>1.1.22</version> </dependency> <!-- MyBatis Plus -...
<dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> <versio # 从数据源开关/默认关闭 driverClassName: ru.yandex.clickhouse.ClickHouseDriver url: jdbc:clickhouse://127.0.0.1:8123/test usern
<think>好的,我现在需要帮助用户在Spring Boot项目中集成MyBatis-PlusDruid来实现多数据源配置。首先,我要理清楚用户的需求:他们想要在应用中使用这两个技术栈,并且能够切换和管理多个数据源。接下来,我需要回忆一下相关的知识,并结合提供的引用内容来构建答案。 首先,用户提到了MyBatis-PlusDruid,这两个都是常用的Java库。MyBatis-Plus是对MyBatis的增强,提供了很多便捷的功能,比如CRUD接口、条件构造器等。Druid是阿里巴巴开源的数据库连接池,提供了强大的监控和扩展功能。结合这两个工具,可以有效地管理数据库连接和操作。 接下来,用户需要多数据源的支持。多数据源配置通常涉及多个数据源的实例化,以及在不同情况下切换使用不同的数据源。在Spring Boot中,默认的数据源是自动配置的,但多数据源需要手动配置,并且需要解决事务管理等问题。 根据引用[1]和[2],用户可能需要整合sharding-jdbc-spring-boot-starter、mybatis-plus-boot-starter和druid。不过用户的问题主要集中在多数据源的切换和管理,所以可能需要分步骤讲解如何配置多个数据源,每个数据源使用Druid作为连接池,并且通过MyBatis-Plus来操作数据库。 首先,我应该考虑添加依赖。用户的项目需要引入MyBatis-PlusDruid以及可能的动态数据源依赖,比如dynamic-datasource-spring-boot-starter,这个库可以帮助简化多数据源配置。不过引用中没有提到这个,可能需要结合常见的做法。 然后,配置数据源信息。在application.yml中定义两个数据源,比如master和slave,分别配置它们的url、username、password等信息,并且指定使用Druid作为连接池类型。 接下来,创建数据源配置类。使用@Configuration和@Bean注解来创建两个不同的DataSource实例,并且为每个数据源配置Druid的相关属性,比如过滤器、监控统计等。同时,需要设置@Primary注解来指定主数据源。 然后,配置MyBatis-Plus。每个数据源对应的SqlSessionFactory和事务管理器需要分别配置,并且指定不同的Mapper包路径,以便区分不同数据源的DAO层。 在业务层,需要使用@DS注解(来自dynamic-datasource)来指定具体使用哪个数据源。这样在Service层的方法上添加注解即可切换数据源。 事务管理方面,需要注意每个数据源的事务管理器要正确配置,避免跨数据源事务的问题。通常,在多数据源环境下,分布式事务处理比较复杂,可能需要额外的事务管理器,但用户的问题可能暂时不需要涉及这个,可以建议在需要的时候使用JTA或其他解决方案。 最后,测试验证,确保两个数据源都能正常工作,并且能够根据注解切换。 现在,我需要检查是否有遗漏的步骤,比如是否需要在启动类上排除默认的数据源自动配置,避免冲突。另外,动态数据源的选择是否需要额外的配置,比如AOP切面或者自定义的注解处理器。 可能还需要考虑Druid监控界面的配置,让用户能够访问Druid提供的监控页面,查看数据源的状态和SQL执行情况。 总结下来,步骤应该是: 1. 添加相关依赖(MyBatis-PlusDruid、动态数据源starter) 2. 配置多数据源信息 3. 排除默认数据源,手动配置每个数据源的Bean 4. 配置MyBatis-Plus的SqlSessionFactory和Mapper扫描 5. 使用@DS注解切换数据源 6. 配置事务管理器 7. 启用Druid监控 8. 测试验证 同时,需要提醒用户注意事务管理和连接池配置的最佳实践,比如合理设置连接池参数,监控SQL性能等。 可能的问题包括依赖冲突、配置错误导致数据源无法正确注入,或者事务不生效。需要确保每一步配置正确,并且依赖版本兼容。 最后,生成相关问题,可能涉及性能优化、监控配置、事务管理深入等方向。</think>### 分步实现Spring Boot集成MyBatis-PlusDruid多数据源配置 #### 一、添加依赖 在`pom.xml`中引入以下依赖: ```xml <!-- MyBatis-Plus --> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> <version>3.5.2</version> </dependency> <!-- Druid连接池 --> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid-spring-boot-starter</artifactId> <version>1.2.16</version> </dependency> <!-- 动态数据源(支持多数据源切换) --> <dependency> <groupId>com.baomidou</groupId> <artifactId>dynamic-datasource-spring-boot-starter</artifactId> <version>3.5.1</version> </dependency> #### 二、配置多数据源信息 在`application.yml`中定义数据源: ```yaml spring: datasource: dynamic: primary: master # 默认主数据源 strict: false # 允许非明确标注时使用主数据源 datasource: master: url: jdbc:mysql://localhost:3306/db1 username: root password: 123456 driver-class-name: com.mysql.cj.jdbc.Driver type: com.alibaba.druid.pool.DruidDataSource slave: url: jdbc:mysql://localhost:3306/db2 username: root password: 123456 driver-class-name: com.mysql.cj.jdbc.Driver type: com.alibaba.druid.pool.DruidDataSource # Druid监控配置 druid: stat-view-servlet: enabled: true url-pattern: /druid/* login-username: admin login-password: admin #### 三、配置数据源与MyBatis-Plus 1. **主数据源配置类** ```java @Configuration @MapperScan(basePackages = "com.example.mapper.master", sqlSessionFactoryRef = "masterSqlSessionFactory") public class MasterDataSourceConfig { @Bean("master") @ConfigurationProperties(prefix = "spring.datasource.dynamic.datasource.master") public DataSource masterDataSource() { return DruidDataSourceBuilder.create().build(); @Bean("masterSqlSessionFactory") public SqlSessionFactory masterSqlSessionFactory(@Qualifier("master") DataSource dataSource) throws Exception { MybatisSqlSessionFactoryBean factoryBean = new MybatisSqlSessionFactoryBean(); factoryBean.setDataSource(dataSource); return factoryBean.getObject(); @Bean("masterTransactionManager") public PlatformTransactionManager masterTransactionManager(@Qualifier("master") DataSource dataSource) { return new DataSourceTransactionManager(dataSource); 2. **从数据源配置类**(结构与主数据源类似,替换包路径和Bean名称) #### 四、使用@DS注解切换数据源 在Service层方法上标注`@DS("slave")`: ```java @Service public class UserService { @Autowired private UserMapper userMapper; @DS("master") // 默认使用主数据源 public void addUser(User user) { userMapper.insert(user); @DS("slave") // 切换至从数据源 public User getUserById(Long id) { return userMapper.selectById(id); #### 五、启用Druid监控 访问`http://localhost:8080/druid`输入配置的用户名密码即可查看监控信息[^1]。 #### 六、事务管理 - 单数据源事务:使用`@Transactional`注解,默认绑定主数据源事务管理器 - 跨数据源事务:需引入分布式事务框架(如Seata)或使用JTA --- ### 注意事项 1. 确保各数据源的`Mapper`接口和`XML`文件路径隔离(如`com.example.mapper.master`和`com.example.mapper.slave`) 2. 动态数据源依赖需与MyBatis-Plus版本兼容 3. 生产环境中建议配置Druid连接池参数(如`initialSize`、`maxActive`) ---