SoFunction
Updated on 2025-03-09

Implementation of MyBatis-Plus Plugin Extension

MyBatis-Plus provides rich plug-in expansion mechanisms, allowing developers to implement enhanced functions or customized operations through plug-ins. Through the plug-in mechanism, developers can easily expand the functionality of MyBatis-Plus to meet complex business needs.

1. How the MyBatis-Plus plug-in works

The plug-in mechanism of MyBatis-Plus is based on the provided by MyBatisInterceptorInterceptor. The MyBatis interceptor can intercept and enhance MyBatis' four core objects:

  • Executor: Responsible for executing SQL statements, such as adding, deleting, modifying, and searching.
  • StatementHandler: Responsible for handling SQL statement generation and parameter setting.
  • ResultSetHandler: Responsible for processing the result set after SQL statement execution.
  • ParameterHandler: Responsible for handling parameter binding in SQL statements.

The plug-in mechanism of MyBatis-Plus is extended based on the MyBatis interceptor. Through plug-ins, developers can intercept, modify and optimize SQL execution processes.

2. MyBatis-Plus commonly used plug-ins

MyBatis-Plus provides many built-in plug-ins to help developers quickly achieve common functional needs.

1. Pagination plugin

Pagination query is a common requirement in database operations. MyBatis-Plus provides a paging plugin that automatically generates paging SQL for paging queries, avoiding handwritten paging logic.

Configure the paging plugin:

existMyBatisPlusConfigConfigure the paging plugin:

@Configuration
public class MyBatisPlusConfig {

    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        // Configure the paging plugin        (new PaginationInnerInterceptor());
        return interceptor;
    }
}

Pagination query code example:

Page<User> page = new Page<>(1, 10);  // Page 1, 10 items per pageLambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
(User::getAge, 18);
Page<User> userPage = (page, queryWrapper);

selectPageThe data will be queryed based on the paging SQL generated by the paging plug-in, and the result will be returned to include detailed information about the paging, such as the total number of entries, the total number of pages, etc.

2. Logical deletion plug-in

Logical deletion allows the marking of records as deleted without deleting database records. MyBatis-Plus provides built-in logical deletion support, which can be achieved through simple configuration.

Configure logic deletion plugin:

First, define logical delete fields in the entity class and use@TableLogicAnnotation marks:

@Data
public class User {
    private Long id;
    private String name;
    private Integer age;

    // Logical delete field    @TableLogic
    private Integer deleted;
}

existDelete the configuration logic in the  :

mybatis-plus:
  global-config:
    db-config:
      logic-delete-field: deleted  # Set logical deletion fields

When calleddeleteByIdWhen the method, MyBatis-Plus will not really delete the data, but willdeletedField is set to 1:

(1L);  // Actual execution: UPDATE user SET deleted = 1 WHERE id = 1

At the same time, MyBatis-Plus will automatically filter logically deleted records during query.

3. SQL Performance Analysis Plug-in

The SQL performance analysis plug-in is used to analyze SQL execution performance in the development environment, helping developers optimize SQL queries.

Configure SQL Performance Analysis Plug-in:

@Configuration
public class MyBatisPlusConfig {

    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        // Configure performance analysis plug-in        (new PerformanceInnerInterceptor());
        return interceptor;
    }
}

When enabled, the SQL Performance Analysis plug-in will output the time of each SQL execution in the console, making it easier for developers to optimize query performance.

4. Optimistic lock plug-in

Optimistic locks are used to solve concurrency problems. MyBatis-Plus provides a built-in Optimistic lock plug-in to control the update of data through the version number.

Configure the optimistic lock plugin:

Define the version number field in the entity class and use@VersionNote:

@Data
public class User {
    private Long id;
    private String name;
    private Integer age;

    @Version
    private Integer version;
}

Register an optimistic lock plugin in the configuration class:

@Configuration
public class MyBatisPlusConfig {

    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        // Configure the optimistic lock plug-in        (new OptimisticLockerInnerInterceptor());
        return interceptor;
    }
}

During the update operation, MyBatis-Plus will automatically check the version number to ensure that the data will not be overwritten during concurrency.

3. Custom plug-ins

In addition to using the built-in plug-ins provided by MyBatis-Plus, developers can also write custom plug-ins according to their business needs. Custom plug-ins can intercept SQL statements or operation logic during MyBatis execution to enhance functionality.

1. Custom plug-in steps

Custom plugins usually require the following steps:

  • accomplishInterceptorInterface: Define a class that implements MyBatisInterceptorInterface, overwriteintercept()Method, write interception logic.
  • Register a plug-in: Register a custom plug-in to MyBatis-Plus.

2. Custom plugin example

Below we implement a simple custom plug-in for outputting SQL statements to the console before SQL execution.

public class MyCustomInterceptor implements Interceptor {

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        // Get the executed SQL statement        Object[] args = ();
        MappedStatement mappedStatement = (MappedStatement) args[0];
        BoundSql boundSql = (args[1]);
        String sql = ();
        ("Executed SQL:" + sql);

        // Perform the original operation        return ();
    }

    @Override
    public Object plugin(Object target) {
        return (target, this);
    }

    @Override
    public void setProperties(Properties properties) {
    }
}

3. Register a custom plug-in

Register custom plugins into MyBatis-Plus configuration:

@Configuration
public class MyBatisPlusConfig {

    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        // Register custom plugin        (new MyCustomInterceptor());
        return interceptor;
    }
}

After running the application, the custom plug-in intercepts and outputs SQL to the console every time the SQL statement is executed.

4. Things to note when expanding plug-in

  • Plugin order: MyBatis-Plus supports multiple plugins, and multiple plugins will be executed in the order of registration. When writing custom plugins, developers should pay attention to the order of execution of plugins to avoid conflicts between plugins.

  • Performance Impact: While plug-ins can enhance the functionality of MyBatis-Plus, too many plug-ins may have a performance impact, especially in high concurrency scenarios, unnecessary plug-ins should be avoided.

  • Usage scenario: MyBatis-Plus' plug-in mechanism is suitable for a variety of scenarios. Developers can choose the right plug-in according to their business needs, or customize the plug-in to enhance the functions of MyBatis-Plus. But it should be noted that plug-ins are mainly suitable for SQL execution related function extensions, and should be carried out at the business level for complex business logic processing.

5. Summary

MyBatis-Plus provides a powerful plug-in extension mechanism, through which common functions such as paging, logical deletion, SQL performance analysis, and optimistic locking can be easily implemented. The built-in plug-in of MyBatis-Plus has covered most development needs, and developers only need simple configuration to use it. If there are special business needs, developers can also intervene and extend the SQL execution process of MyBatis-Plus by implementing custom plugins.

This is the end of this article about the implementation of the MyBatis-Plus plug-in extension. For more related contents of MyBatis-Plus plug-in extension, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!