数据访问:MyBatis-Plus&Druid数据源

MyBatis-Plus 和 Druid 是 Java 开发中常用的两个库,它们分别用于简化数据库操作和提供强大的数据库连接池功能。MyBatis-Plus 是 MyBatis 的增强工具,在 MyBatis 的基础上只做增强不做改变,为简化开发、提高效率而生。Druid 是一个开源的数据库连接池,它提供了强大的监控和扩展功能,是阿里巴巴开源的数据库连接池项目。

MyBatis-Plus

MyBatis-Plus 继承 MyBatis 的所有特性并强化了很多功能,如内置分页插件、性能分析插件、乐观锁插件、逻辑删除插件等。使用 MyBatis-Plus 可以极大地减少开发工作量,提高开发效率。

引入 MyBatis-Plus

在 Maven 项目中,你可以通过添加以下依赖来引入 MyBatis-Plu

<dependency>  
    <groupId>com.baomidou</groupId>  
    <artifactId>mybatis-plus-boot-starter</artifactId>  
    <version>版本号</version>  
</dependency>
配置 MyBatis-Plus

在 Spring Boot 项目中,你可以通过 application.yml 或 application.properties 文件来配置 MyBatis-Plus。例如:

mybatis-plus:  
  mapper-locations: classpath:/mapper/**/*.xml  
  type-aliases-package: com.example.demo.entity  
  global-config:  
    db-config:  
      id-type: auto  
      table-prefix: t_  
  configuration:  
    map-underscore-to-camel-case: true  
    cache-enabled: false

Druid

Druid 不仅可以作为数据库连接池使用,还提供了强大的监控和扩展功能,如 SQL 监控、URI 监控、Session 监控、JDBC 属性设置等。

引入 Druid

在 Maven 项目中,你可以通过添加以下依赖来引入 Druid

<dependency>  
    <groupId>com.alibaba</groupId>  
    <artifactId>druid-spring-boot-starter</artifactId>  
    <version>版本号</version>  
</dependency>
配置 Druid

在 Spring Boot 项目中,你可以通过 application.yml 或 application.properties 文件来配置 Druid。

spring:  
  datasource:  
    type: com.alibaba.druid.pool.DruidDataSource  
    driver-class-name: com.mysql.cj.jdbc.Driver  
    url: jdbc:mysql://localhost:3306/yourdb?useUnicode=true&characterEncoding=utf8&serverTimezone=UTC  
    username: yourusername  
    password: yourpassword  
    druid:  
      initial-size: 5  
      max-active: 10  
      min-idle: 5  
      max-wait: 10000  
      stat-view-servlet:  
        enabled: true  
        url-pattern: /druid/*  
        login-username: admin  
        login-password: admin  
      filter:  
        stat:  
          enabled: true  
        wall:  
          enabled: true

结合使用

在 Spring Boot 项目中,你可以同时引入 MyBatis-Plus 和 Druid,并通过上述配置来同时使用它们。MyBatis-Plus 负责数据库操作的简化,而 Druid 负责数据库连接池的管理和监控。

总结

MyBatis-Plus 和 Druid 是 Java 开发中非常实用的两个库,它们分别解决了数据库操作和数据库连接池管理的问题。通过合理的配置和使用,可以极大地提高开发效率和系统性能。

首先,需要在pom.xml中添加依赖,如下: ```xml <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> <version>${mybatis-plus.version}</version> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid-spring-boot-starter</artifactId> <version>1.2.6</version> </dependency> ``` 然后,需要在application.yml中配置Druid数据源Mybatis-plus的配置,如下: ```yaml spring: datasource: type: com.alibaba.druid.pool.DruidDataSource driver-class-name: com.mysql.cj.jdbc.Driver url: jdbc:mysql://localhost:3306/db1?useUnicode=true&characterEncoding=utf-8&serverTimezone=GMT%2B8 username: root password: root druid: max-active: 20 initial-size: 1 max-wait: 60000 min-idle: 1 time-between-eviction-runs-millis: 60000 min-evictable-idle-time-millis: 300000 validation-query: SELECT 1 FROM DUAL test-while-idle: true test-on-borrow: false test-on-return: false mybatis-plus: mapper-locations: classpath:/mapper/*.xml global-config: db-config: id-type: auto field-strategy: not_empty table-prefix: t_ logic-delete-value: 1 logic-not-delete-value: 0 configuration: map-underscore-to-camel-case: true ``` 接着,我们需要创建一个数据源切换的工具类,如下: ```java public class DynamicDataSourceContextHolder { private static final ThreadLocal<String> CONTEXT_HOLDER = new ThreadLocal<>(); public static void setDataSourceType(String dataSourceType) { CONTEXT_HOLDER.set(dataSourceType); } public static String getDataSourceType() { return CONTEXT_HOLDER.get(); } public static void clearDataSourceType() { CONTEXT_HOLDER.remove(); } } ``` 然后,我们需要创建一个切面,用来在方法执行前切换数据源,如下: ```java @Component @Aspect public class DynamicDataSourceAspect { @Pointcut("@annotation(com.example.demo.annotation.DataSource)") public void dataSourcePointCut() {} @Around("dataSourcePointCut()") public Object around(ProceedingJoinPoint point) throws Throwable { MethodSignature signature = (MethodSignature) point.getSignature(); DataSource dataSource = signature.getMethod().getAnnotation(DataSource.class); if (dataSource == null) { DynamicDataSourceContextHolder.setDataSourceType("db1"); } else { DynamicDataSourceContextHolder.setDataSourceType(dataSource.value()); } try { return point.proceed(); } finally { DynamicDataSourceContextHolder.clearDataSourceType(); } } } ``` 在需要使用不同数据源的方法上,我们可以使用@DataSource注解来指定数据源,如下: ```java @DataSource("db2") public List<User> selectUserList() { return userMapper.selectList(null); } ``` 最后,我们需要在配置类中配置多个数据源,如下: ```java @Configuration public class DataSourceConfig { @Bean @ConfigurationProperties("spring.datasource.druid.db1") public DataSource db1() { return DruidDataSourceBuilder.create().build(); } @Bean @ConfigurationProperties("spring.datasource.druid.db2") public DataSource db2() { return DruidDataSourceBuilder.create().build(); } @Bean @Primary public DataSource dataSource(DataSource db1, DataSource db2) { Map<Object, Object> targetDataSources = new HashMap<>(); targetDataSources.put("db1", db1); targetDataSources.put("db2", db2); DynamicRoutingDataSource dataSource = new DynamicRoutingDataSource(); dataSource.setTargetDataSources(targetDataSources); dataSource.setDefaultTargetDataSource(db1); return dataSource; } } ``` 以上就是Mybatis-plus切换Druid数据源的完整代码和配置文件配置。其中,DynamicRoutingDataSource是动态数据源的实现类,需要自行实现。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值