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

一、MyBatis-plus 简介

MyBatis-plus(简称 MP)是一个基于 MyBatis 的增强工具包,它在 MyBatis 的基础上进行了大量的扩展和优化,提供了更加便捷、高效的开发体验。

MP 提供了一系列的通用 Mapper 接口,几乎涵盖了所有常见的数据库操作,如插入、更新、删除、查询等。通过这些接口,开发者无需再编写繁琐的 SQL 语句,大大提高了开发效率。

例如,使用 MP 的 BaseMapper 接口,我们可以轻松地实现对数据库表的基本增删改查操作:

public interface UserMapper extends BaseMapper<User> {}

// 插入数据
User user = new User();
user.setName("张三");
user.setAge(20);
userMapper.insert(user);

// 更新数据
User updateUser = new User();
updateUser.setId(1L);
updateUser.setName("李四");
userMapper.updateById(updateUser);

// 删除数据
userMapper.deleteById(1L);

// 查询数据
List<User> userList = userMapper.selectList(null);

2. 丰富的插件支持

MP 内置了许多实用的插件,如分页插件、乐观锁插件、性能分析插件等。这些插件可以轻松地集成到项目中,为开发过程提供更多的便利和保障。

以分页插件为例,只需简单地配置一下,即可实现分页查询功能:

@Configuration
public class MybatisPlusConfig {

    @Bean
    public PaginationInterceptor paginationInterceptor() {
        return new PaginationInterceptor();
    }
}

3. 代码生成器

MP 还提供了强大的代码生成器,可以根据数据库表结构自动生成实体类、Mapper 接口、Service 接口以及对应的实现类。这极大地减少了开发者的工作量,提高了开发效率,同时也保证了代码的规范性和一致性。

二、Druid 数据源简介

Druid 是阿里巴巴开源的一款数据库连接池,它具有强大的监控和管理功能,能够有效地提升数据库访问性能和稳定性。

1. 高性能

Druid 采用了一系列的优化技术,如连接池的预初始化、连接的复用、SQL 语句的缓存等,大大提高了数据库连接的获取速度和执行效率。

2. 丰富的监控信息

Druid 提供了非常丰富的监控信息,包括连接池的使用情况、SQL 执行的统计信息、慢查询日志等。通过这些监控信息,开发者可以及时发现和解决系统中可能存在的性能问题。

3. 强大的扩展性

Druid 具有良好的扩展性,支持自定义扩展插件,可以根据实际需求对连接池进行定制化开发。

三、MyBatis-plus 与 Druid 数据源的整合

将 MyBatis-plus 与 Druid 数据源整合在一起,可以充分发挥两者的优势,实现更高效、更稳定的数据访问。

1. 添加依赖

首先,在项目的 pom.xml 文件中添加 MyBatis-plus 和 Druid 数据源的依赖

<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus-boot-starter</artifactId>
    <version>3.5.5.1</version>
</dependency>
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid-spring-boot-starter</artifactId>
    <version>1.2.21</version>
</dependency>

2. 配置数据源

在 application.properties 文件中配置 Druid 数据源:

spring:
  #配置数据源
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/crm?useUnicode=true&characterEncoding=utf-8
    username: root
    password: 123456
    type: com.alibaba.druid.pool.DruidDataSource #使用阿里巴巴Druid数据源
    druid:
      ############ 连接池基础配置 ############
      initial-size: 1 #初始化大小
      max-active: 20 #最大连接数
      min-idle: 1 #最小连接数
      max-wait: 60000 #获取连接等待超时的时间(单位:毫秒)
      time-between-eviction-runs-millis: 60000 #间隔多久检测一次需要关闭的空闲连接(单位:毫秒)
      time-between-log-stats-millis: 60000 #日志统计信息之间的时间(单位:毫秒)
      min-evictable-idle-time-millis: 300000 #一个连接在池中最小生存的时间(单位:毫秒)
      max-evictable-idle-time-millis: 600000 #一个连接在池中最大生存的时间(单位:毫秒)
      test-while-idle: true #应用向连接池申请连接,值为false时,连接池将会判断连接是否处于空闲状态,如果是则验证这条连接是否可用
      test-on-borrow: false #默认值为false,如果为true,应用向连接池申请连接时连接池会判断这条连接是否是可用的
      test-on-return: false #默认值为false,如果为true,当应用使用完连接,连接池回收连接的时候会判断该连接是否还可用
      validation-query: select 1 #用来测试连接是否可用的SQL语句
      validation-query-timeout: 60000 #连接是否可用测试超时时间(单位:毫秒)
#      use-global-datasource-stat: true #使用全局数据源统计
      keep-alive: true #连接池中的min-idle数量以内的连接,空闲时间超过max-evictable-idle-time-millis,则会执行KeepAlive操作
      pool-prepared-statements: true #是否缓存PreparedStatement,也就是PSCache,对支持游标的数据库性能提升巨大,比如Oracle
      max-open-prepared-statements: 20 #要启用PSCache,必须配置大于0(当大于0时,pool-prepared-statements自动触发修改为true)在Druid中,不会存在Oracle下PSCache占用内存过多的问题,可以把这个数值配置大一些,比如100
      connection-properties: stat.mergeSql=true;stat.slowSqlMillis=5000 #设置连接属性,mergeSql合并SQL,慢SQL时长定义(单位:毫秒)
      remove-abandoned: true #开启连接池回收(针对不活跃的连接)
      remove-abandoned-timeout: 1800 #超时连接回收时间(单位:毫秒)
      log-abandoned: true #回收连接时打印日志
      ############ 数据库连接监控 ############
      aop-patterns: "com.bdqn.*.mapper.*" #Spring监控,利用AOP对指定接口的执行时间,JDBC数进行记录
      filters: stat,wall,log4j2 #启用内置过滤器(第一个 stat必须,否则监控不到SQL)
      filter: #监控统计拦截器
        stat: #开启DruidDataSource的状态监控
          enabled: true #启用DruidDataSource状态监控
          db-type: mysql #数据库类型
          log-slow-sql: true #开启慢SQL监控
          slow-sql-millis: 2000 #超过2s就认为是慢SQL,记录到日志中
        slf4j: #日志监控,使用slf4j进行日志输出
          enabled: true #启用日志监控
          statement-log-error-enabled: true
          statement-create-after-log-enabled: false
          statement-close-after-log-enabled: false
          result-set-open-after-log-enabled: false
          result-set-close-after-log-enabled: false
      web-stat-filter: #配置WebStatFilter,用于采集Web关联监控的数据
        enabled: true #启用WebStatFilter
        url-pattern: /* #过滤所有URL
        exclusions: "*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*" #排除一些不必要的URL
        session-stat-enable: true #开启Session统计功能
        session-stat-max-count: 100 #Session的最大个数(默认100)
      stat-view-servlet: #配置StatViewServlet(监控页面),用于展示Druid的统计信息
        enabled: true #启用StatViewServlet(监控页面)
        url-pattern: /druid/* #访问内置监控页面的路径,内置监控页面的首页是/druid/index.html
        reset-enable: false #不允许清空统计数据,重新计算
        login-username: admin #监控页面访问账号
        login-password: admin #监控页面访问密码
        allow: 127.0.0.1,localhost #允许访问的地址,如果allow没有配置或者为空,则允许所有访问
        deny: #拒绝访问的地址,deny优先于allow,如果在deny列表中,就算在allow列表中,也会被拒绝

#配置mybatis相关信息
#mybatis:
#  config-location: classpath:mybatis/mybatis-config.xml
#  mapper-locations: classpath:mybatis/mapper/*.xml
#  type-aliases-package: com.bdqn.demo.pojo


  #配置前端页面访问路径前缀和后缀
  mvc:
    view:
      prefix: /WEB-INF/jsp/templates/
      suffix: .jsp

  #spring.jpa.properties.hibernate.
  #指定数据库方言
  jpa:
    properties:
      hibernate:
        #配置jpa(Hibernate)相关信息
        hbm2ddl:
          auto: update
          #指定hibernate方言
        dialect: org.hibernate.dialect.MySQLDialect
  #格式化sql语句,默认false,这个配置需要配合spring.jpa.show-sql=true使用,默认的sql语句是带括号的,开启这个配置后语句会换行
        format_sql: true
  #是否在日志中打印出自动生成的sql,方便调试的时候查看
    show-sql: true



#配置日志
logging:
  level:
    root: warn
    com.bdqn.demo.mapper: trace
  pattern:
    console: '%p%m%n'


3. 使用 MyBatis-plus 和 Druid 数据源

完成上述配置后,我们就可以在项目中使用 MyBatis-plus 和 Druid 数据源了。在代码中,我们只需注入 Mapper 接口,即可进行数据库操作:

@Service
public class UserService {

    @Autowired
    private UserMapper userMapper;

    public List<User> getUserList() {
        return userMapper.selectList(null);
    }
}
  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
首先,需要在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、付费专栏及课程。

余额充值