深入 MyBatis-Plus 插件:解锁高级数据库功能

本文涉及的产品
RDS MySQL Serverless 基础系列,0.5-2RCU 50GB
日志服务 SLS,月写入数据量 50GB 1个月
云数据库 RDS PostgreSQL,高可用系列 2核4GB
简介: Mybatis-Plus 提供了丰富的插件机制,这些插件可以帮助开发者更方便地扩展 Mybatis 的功能,提升开发效率、优化性能和实现一些常用的功能。

一、关于Mybatis-Plus插件

1.1 简介

Mybatis-Plus 提供了丰富的插件机制,这些插件可以帮助开发者更方便地扩展 Mybatis 的功能,提升开发效率、优化性能和实现一些常用的功能。

953921f3-2296-4535-9f98-4d4c3d801e2d

1.2 实现原理

Mybatis-Plus 的插件实现是基于 MyBatis 的拦截器机制, 这些插件通过 MybatisPlusInterceptor​ 来实现对 MyBatis 执行过程的拦截和增强。

MyBatis 插件本质上是对 SQL 执行过程的拦截和扩展,Mybatis-Plus 插件通过在 MyBatis 的执行生命周期中插入拦截器来实现一些增强功能。通过这种方式,Mybatis-Plus 可以实现分页、性能分析、乐观锁等功能的自动化处理。

MybatisPlusInterceptor 概览

MybatisPlusInterceptor​ 是 MyBatis-Plus 的核心插件,它代理了 MyBatis 的 Executor#query​、Executor#update​ 和 StatementHandler#prepare​ 方法,允许在这些方法执行前后插入自定义逻辑。

image

属性

MybatisPlusInterceptor​ 有一个关键属性 interceptors​,它是一个 List<InnerInterceptor>​ 类型的集合,用于存储所有要应用的内部拦截器。

InnerInterceptor 接口

所有 MyBatis-Plus 提供的插件都实现了 InnerInterceptor​ 接口,这个接口定义了插件的基本行为。目前,MyBatis-Plus 提供了以下插件:

  • 自动分页: PaginationInnerInterceptor
  • 多租户: TenantLineInnerInterceptor
  • 动态表名: DynamicTableNameInnerInterceptor
  • 乐观锁: OptimisticLockerInnerInterceptor
  • SQL 性能规范: IllegalSQLInnerInterceptor
  • 防止全表更新与删除: BlockAttackInnerInterceptor

1.3 配置方式

插件的配置可以在 Spring 配置中进行,也可以在 Spring Boot 项目中通过 Java 配置来添加。以下是两种配置方式的示例:

  • Spring 配置:在 Spring 配置中,需要创建 MybatisPlusInterceptor​ 的实例,并将它添加到 MyBatis 的插件列表中。
  • Spring Boot 配置:在 Spring Boot 项目中,可以通过 Java 配置来添加插件,例如添加分页插件。

Spring Boot 配置示例

@Configuration
@MapperScan("scan.your.mapper.package")
public class MybatisPlusConfig {
   

    /**
     * 添加分页插件
     */
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
   
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
        return interceptor;
    }
}

配置多个插件

@Configuration
public class MyBatisPlusConfig {
   

    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
   
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();

        // 添加分页插件
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));

        // 添加性能分析插件
        PerformanceInterceptor performanceInterceptor = new PerformanceInterceptor();
        performanceInterceptor.setMaxTime(1000); // 设置SQL最大执行时间,单位为毫秒
        interceptor.addInnerInterceptor(performanceInterceptor);

        // 添加防全表更新与删除插件
        interceptor.addInnerInterceptor(new BlockAttackInnerInterceptor());

        return interceptor;
    }
}

注意

使用多个插件时,需要注意它们的顺序。建议的顺序是:

  1. 多租户、动态表名
  2. 分页、乐观锁
  3. SQL 性能规范、防止全表更新与删除

总结:对 SQL 进行单次改造的插件应优先放入,不对 SQL 进行改造的插件最后放入。

二、分页插件(PaginationInnerInterceptor​)

2.1 关于

简介

MyBatis-Plus 的分页插件 PaginationInnerInterceptor​ 提供了强大的分页功能,支持多种数据库,使得分页查询变得简单高效。用时只需要在查询方法中传入Page<T>​对象,插件会自动处理分页相关的SQL构建和结果集解析。

image

主要功能

  1. 自动分页

    • 通过在查询时自动添加 LIMIT​ 和 OFFSET​ 等 SQL 关键字,来实现分页功能。
  2. 兼容性

    • 支持多种数据库的分页语法,确保在不同数据库上都能正常工作。
  3. 动态参数

    • 可以动态地根据用户的请求参数(如页码和每页大小)生成分页信息,而无需手动处理 SQL。
  4. 性能优化

    • 在执行分页查询时,通过设置合理的参数,能够减少查询的时间复杂度,提高查询效率。

关键参数

  • DbType:指定数据库类型,影响生成的分页 SQL 语句。例如,DbType.MYSQL​ 会生成适用于 MySQL 的分页语句。
  • setOverflow:允许配置是否允许请求的页码超出最大页码范围(例如,返回最后一页的数据)。
  • setMaxLimit:可以设置每页最大记录数,避免用户请求过大的分页数据。

2.2 使用

配置插件

@Configuration
@MapperScan("scan.your.mapper.package")
public class MybatisPlusConfig {
   

    /**
     * 添加分页插件
     */
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
   
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL)); // 如果配置多个插件, 切记分页最后添加
        // 如果有多数据源可以不配具体类型, 否则都建议配上具体的 DbType
        return interceptor;
    }
}

分页查询

Page<User> page = new Page<>(1, 10);  // 当前页, 每页记录数
IPage<User> userPage = userMapper.selectPage(page, null);

三、性能分析插件(PerformanceInterceptor​)

3.1 关于

简介

性能分析插件(PerformanceInterceptor​)是 MyBatis-Plus 提供的一个非常有用的工具,它可以用来监控 SQL 语句的执行时间,帮助开发者及时发现和优化慢查询问题。

3.2 使用

配置插件

import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PerformanceInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class MyBatisPlusConfig {
   

    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
   
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        // 添加性能分析插件
        PerformanceInterceptor performanceInterceptor = new PerformanceInterceptor();
        performanceInterceptor.setMaxTime(1000); // 设置SQL最大执行时间,单位为毫秒
        interceptor.addInnerInterceptor(performanceInterceptor);
        return interceptor;
    }
}

配置日志输出

为了更好地监控 SQL 语句的执行情况,可以配置日志输出。在 application.properties​ 或 application.yml​ 文件中添加日志配置:

logging:
  level:
    com.baomidou.mybatisplus: DEBUG

  • SQL 执行时间记录:每次执行 SQL 语句时,插件会记录执行时间。
  • 超时处理:如果 SQL 语句的执行时间超过 setMaxTime​ 方法设置的阈值(默认为 0,表示不限制),插件会记录一条警告日志或抛出异常,具体行为取决于配置。

如果 SQL 语句执行时间超过设定的阈值,日志输出可能如下所示:

2024-11-08 10:41:00 [http-nio-8080-exec-1] WARN  c.b.mybatisplus.extension.plugins.inner.PerformanceInterceptor - [performance] SQL Execution Time: 1500 ms

通过以上步骤,你可以在 MyBatis-Plus 中轻松配置和使用性能分析插件,帮助你及时发现和优化慢查询问题。

四、防全表更新与删除插件(BlockAttackInterceptor​)

4.1 关于

简介

MyBatis-Plus 提供了一个防全表更新与删除插件(BlockAttackInterceptor​),该插件可以防止在没有 WHERE 条件的情况下执行全表更新或删除操作,从而避免误操作导致的数据丢失或损坏

使用

配置插件

import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.BlockAttackInnerInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class MyBatisPlusConfig {
   

    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
   
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        // 添加防全表更新与删除插件
        interceptor.addInnerInterceptor(new BlockAttackInnerInterceptor());
        return interceptor;
    }
}

测试

在控制器层中调用 Service 层的方法进行查询。

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@RequestMapping("/users")
public class UserController {
   

    @Autowired
    private UserService userService;

    @PostMapping("/delete-all")
    public String deleteAllUsers() {
   
        try {
   
            userService.remove(null); // 尝试删除所有用户
            return "All users deleted successfully";
        } catch (Exception e) {
   
            return "Failed to delete all users: " + e.getMessage();
        }
    }

    @PostMapping("/update-all")
    public String updateAllUsers() {
   
        try {
   
            User user = new User();
            user.setName("Updated Name");
            userService.updateById(user); // 尝试更新所有用户
            return "All users updated successfully";
        } catch (Exception e) {
   
            return "Failed to update all users: " + e.getMessage();
        }
    }
}
  1. 尝试删除所有用户:访问 /users/delete-all​ 接口。

    • 如果没有 WHERE 条件,插件会抛出异常并阻止删除操作。

    • 控制台输出示例:

      Failed to delete all users: Cannot execute delete operation without where condition!
      
  2. 尝试更新所有用户:访问 /users/update-all​ 接口。

    • 如果没有 WHERE 条件,插件会抛出异常并阻止更新操作。

    • 控制台输出示例:

      Failed to update all users: Cannot execute update operation without where condition!
      

五、自定义插件

如果内置插件不能满足需求,可以自定义插件。自定义插件需要实现 Interceptor​ 或 InnerInterceptor​ 接口,并在 intercept​ 方法中实现自定义逻辑。

示例:

import com.baomidou.mybatisplus.extension.plugins.inner.InnerInterceptor;
import org.apache.ibatis.executor.statement.StatementHandler;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Signature;

import java.sql.Connection;

@Intercepts({
   @Signature(type = StatementHandler.class, method = "prepare", args = {
   Connection.class, Integer.class})})
public class CustomInterceptor implements Interceptor {
   

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
   
        // 自定义逻辑
        System.out.println("CustomInterceptor: Before SQL execution");
        Object result = invocation.proceed();
        System.out.println("CustomInterceptor: After SQL execution");
        return result;
    }

    @Override
    public Object plugin(Object target) {
   
        return Interceptor.super.plugin(target);
    }

    @Override
    public void setProperties(Properties properties) {
   
        Interceptor.super.setProperties(properties);
    }
}

注册自定义插件:

@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor() {
   
    MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
    interceptor.addInnerInterceptor(new CustomInterceptor());
    return interceptor;
}

通过上述机制和接口,MyBatis-Plus 提供了灵活的插件扩展能力,使开发者可以根据具体需求定制化功能。

相关实践学习
每个IT人都想学的“Web应用上云经典架构”实战
本实验从Web应用上云这个最基本的、最普遍的需求出发,帮助IT从业者们通过“阿里云Web应用上云解决方案”,了解一个企业级Web应用上云的常见架构,了解如何构建一个高可用、可扩展的企业级应用架构。
MySQL数据库入门学习
本课程通过最流行的开源数据库MySQL带你了解数据库的世界。 &nbsp; 相关的阿里云产品:云数据库RDS MySQL 版 阿里云关系型数据库RDS(Relational Database Service)是一种稳定可靠、可弹性伸缩的在线数据库服务,提供容灾、备份、恢复、迁移等方面的全套解决方案,彻底解决数据库运维的烦恼。 了解产品详情:&nbsp;https://www.aliyun.com/product/rds/mysql&nbsp;
目录
相关文章
|
28天前
|
SQL 关系型数据库 MySQL
阿里云RDS云数据库全解析:产品功能、收费标准与活动参考
与云服务器ECS一样,关系型数据库RDS也是很多用户上云必买的热门云产品之一,阿里云的云数据库RDS主要包含RDS MySQL、RDS SQL Server、RDS PostgreSQL、RDS MariaDB等几个关系型数据库,并且提供了容灾、备份、恢复、监控、迁移等方面的全套解决方案,帮助您解决数据库运维的烦恼。本文为大家介绍阿里云的云数据库 RDS主要产品及计费方式、收费标准以及活动等相关情况,以供参考。
|
4月前
|
SQL 存储 关系型数据库
MySQL功能模块探秘:数据库世界的奇妙之旅
]带你轻松愉快地探索MySQL 8.4.5的核心功能模块,从SQL引擎到存储引擎,从复制机制到插件系统,让你在欢声笑语中掌握数据库的精髓!
159 26
|
5月前
|
Java 数据库连接 数据库
Spring boot 使用mybatis generator 自动生成代码插件
本文介绍了在Spring Boot项目中使用MyBatis Generator插件自动生成代码的详细步骤。首先创建一个新的Spring Boot项目,接着引入MyBatis Generator插件并配置`pom.xml`文件。然后删除默认的`application.properties`文件,创建`application.yml`进行相关配置,如设置Mapper路径和实体类包名。重点在于配置`generatorConfig.xml`文件,包括数据库驱动、连接信息、生成模型、映射文件及DAO的包名和位置。最后通过IDE配置运行插件生成代码,并在主类添加`@MapperScan`注解完成整合
873 1
Spring boot 使用mybatis generator 自动生成代码插件
|
6月前
|
存储 缓存 自然语言处理
评论功能开发全解析:从数据库设计到多语言实现-优雅草卓伊凡
评论功能开发全解析:从数据库设计到多语言实现-优雅草卓伊凡
159 8
评论功能开发全解析:从数据库设计到多语言实现-优雅草卓伊凡
|
6月前
|
SQL Java 数据安全/隐私保护
发现问题:Mybatis-plus的分页总数为0,分页功能失效,以及多租户插件的使用。
总的来说,使用 Mybatis-plus 确实可以极大地方便我们的开发,但也需要我们理解其工作原理,掌握如何合适地使用各种插件。分页插件和多租户插件是其中典型,它们的运用可以让我们的代码更为简洁、高效,理解和掌握好它们的用法对我们的开发过程有着极其重要的意义。
620 15
|
8月前
|
SQL Linux 数据库
【YashanDB知识库】崖山数据库Outline功能验证
本文来自YashanDB官网,主要测试了数据库优化器在不同场景下优先使用outline计划的功能。测试环境包括相同版本新增数据、绑定参数执行、单机主备架构以及数据库版本升级等场景。通过创建表、插入数据、收集统计信息和创建outline等步骤,验证了在各种情况下优化器均能优先采用存储的outline计划。测试结果表明,即使统计信息失效或数据库版本升级,outline功能依然稳定有效,确保查询计划的一致性和性能优化。详情可见[原文链接](https://www.yashandb.com/newsinfo/7488286.html?templateId=1718516)。
【YashanDB知识库】崖山数据库Outline功能验证
|
8月前
|
NoSQL 关系型数据库 MongoDB
Apifox与Apipost数据库连接功能详细对比,让接口管理更高效!
在现代软件开发中,数据库是应用运行的核心组件,接口管理工具则是连接和调试数据库的重要桥梁。本文对比了 Apifox 和 Apipost 两款工具的数据库连接功能。Apipost 支持全面的关系型与非关系型数据库(如 MySQL、Redis、MongoDB),功能强大且免费,适合复杂项目;而 Apifox 在关系型数据库支持上表现良好,但非关系型数据库(尤其是 Redis)功能有限且收费,更适合中小项目以关系型数据库为主的需求。根据项目需求选择合适的工具,可显著提升开发效率和稳定性。
|
8月前
|
缓存 NoSQL 关系型数据库
WordPress数据库查询缓存插件
这款插件通过将MySQL查询结果缓存至文件、Redis或Memcached,加速页面加载。它专为未登录用户优化,支持跨页面缓存,不影响其他功能,且可与其他缓存插件兼容。相比传统页面缓存,它仅缓存数据库查询结果,保留动态功能如阅读量更新。提供三种缓存方式选择,有效提升网站性能。
142 1
|
8月前
|
Oracle 关系型数据库 Java
|
8月前
|
SQL 关系型数据库 数据库连接