SoFunction
Updated on 2025-04-13

Implementation of InnerInterceptor in MyBatis Plus

Implementation of InnerInterceptor in MyBatis Plus

Updated: March 17, 2025 09:22:52 Author: Classmate Twelve
This article mainly introduces the implementation of InnerInterceptor in MyBatis Plus. The example code is introduced in this article in detail, which has certain reference learning value for everyone's study or work. Friends who need it, please learn with the editor below.

When using MyBatis Plus in Spring Boot projects, you may encounter the concept of InnerInterceptor. InnerInterceptor is a lightweight SQL interceptor provided by MyBatis Plus. It is different from the traditional MyBatis interceptor. It is simpler and more efficient, and focuses more on interception at the SQL execution level. This article will provide detailed descriptions of the principles, usage, and best practices of InnerInterceptor and provides code examples.

1. Why do you need InnerInterceptor?

  • Lighter: Compared with traditional Interceptor, InnerInterceptor is lighter, reducing unnecessary interception overhead and improving performance.
  • Focus on SQL execution: InnerInterceptor focuses on the SQL execution level, which allows you to modify SQL statements, parameters, or results more conveniently.
  • Simplify configuration: The configuration of InnerInterceptor is simpler, without manual registration, MyBatis Plus will automatically recognize and register.
  • Easy to expand: You can customize SQL interceptor logic by implementing the InnerInterceptor interface.
  • Seamless integration with MyBatis Plus: InnerInterceptor seamlessly integrates with other features of MyBatis Plus to better utilize the advantages of MyBatis Plus.
  • Built-in rich features: MyBatis Plus provides many built-in InnerInterceptor implementations, such as paging plug-ins, optimistic locking plug-ins, SQL performance analysis plug-ins, etc., which can be used directly.

2. The difference between InnerInterceptor and Interceptor

  • Intercept range
    InterceptorIt can intercept MyBatis's Executor, ParameterHandler, ResultSetHandler and StatementHandler components, and the interception range is wider.
    InnerInterceptorThe StatementHandler is mainly intercepted during SQL execution, with a narrower interception range, but is more focused on SQL execution.
  • Execution timing
    InterceptorIt can intercept multiple stages in the SQL execution process, such as parameter processing, SQL precompilation, result processing, etc.
    InnerInterceptorThe prepare and query methods of StatementHandler are mainly intercepted, and focus more on the preparation and execution stages of SQL statements.
  • Configuration method
    InterceptorRequires manual registration in the MyBatis configuration file or Spring Bean.
    InnerInterceptorUnified registration management through MybatisPlusInterceptor provided by MyBatis Plus, no manual registration is required.
  • Code complexity
    InterceptorThe code of  is relatively complex, and it needs to process the Invocation object and manually call the process method.
    InnerInterceptorThe code of  is more concise, you only need to rewrite the corresponding method.
  • performance
    InterceptorDue to the wider interception range, it may bring certain performance overhead.
    InnerInterceptorBecause the interception range is narrower, the performance is higher.

3. The core method of InnerInterceptor

  • void beforePrepare(StatementHandler sh, Connection connection,Integer transactionTimeout): Called before SQL statements are precompiled.
  • void beforeQuery(StatementHandler sh, Connection connection, Integer transactionTimeout): Called before SQL statement is executed.
  • void afterQuery(StatementHandler sh, Connection connection, Integer transactionTimeout, Object result): Called after SQL query is executed.
  • void beforeUpdate(StatementHandler sh, Connection connection, Integer transactionTimeout): Called before executing an INSERT or UPDATE statement.
  • void afterUpdate(StatementHandler sh, Connection connection, Integer transactionTimeout,Object result): Called after executing an INSERT or UPDATE statement.

4. Practice: Use InnerInterceptor to modify SQL statements

4.1 Create the InnerInterceptor implementation class:

import ;
import ;
import .slf4j.Slf4j;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;

import ;
import ;

@Component
@Slf4j
public class MyInnerInterceptor implements InnerInterceptor {

    @Override
    public void beforeQuery(Executor executor, MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, BoundSql boundSql) throws SQLException {
        String sql = ();
        try {
             mpBs = (boundSql);
            //SQL processing            String filterSql = addFilterCondition(sql);
            ("Modifiedsql:{}", filterSql);
            //Modify sql            (filterSql);
        } catch (Exception e) {
            ("Dynamic modificationsql:{}abnormal", sql, e);
            throw new SQLException("Abnormal data permission");
        }
    }

    public String addFilterCondition(String originalSql) throws JSQLParserException {
        CCJSqlParserManager parserManager = new CCJSqlParserManager();
        Select select = (Select) (new StringReader(originalSql));
        PlainSelect plain = (PlainSelect) ();
        Expression where_expression = ();
        // Here you can add filter conditions as needed        if (where_expression == null) {
            (("age = 35"));
        }
        return ();
    }
}

4.2 Configuring MybatisPlusInterceptor

import ;
import ;
import ;
import ;
import ;

import ;
import ;

@Configuration
public class MyBatisPlusConfig {

    @Autowired
    private List<SqlSessionFactory> sqlSessionFactoryList;

    @Autowired
    private MyInnerInterceptor myInnerInterceptor;

    /**
      * Add Mybatis interceptor
      * Mainly to ensure that the data permission interceptor executes SQL modification before the paging plug-in interceptor. If it is not added manually here, PageInterceptor will execute first.
      * Added interceptor and then execute
      */
    @PostConstruct
    public void addMybatisInterceptor() {
        for (SqlSessionFactory sqlSessionFactory : sqlSessionFactoryList) {
             configuration = ();
            //Add data permission interceptor to MybatisPlusInterceptor interceptor chain            MybatisPlusInterceptor mybatisPlusInterceptor = new MybatisPlusInterceptor();
            (myInnerInterceptor);
            //First add the PageHelper paging plugin interceptor, then add the MybatisPlusInterceptor interceptor            //(new PageInterceptor());
            (mybatisPlusInterceptor);
        }
    }
}

4.3 Using InnerInterceptor

Now, any SQL statement you execute will be intercepted by InnerInterceptor, and you can see that the SQL statement has been modified.

Modifiedsql:SELECT count(0) FROM t_user_info WHERE age = 35
Modifiedsql:SELECT id, name, password, age, status, last_login_time, token, create_by, create_time, update_by, update_time, remark FROM t_user_info WHERE age = 35 LIMIT ?

5. Built-in interceptor

In addition to custom interceptors, MyBatis-Plus also offers multiple built-in interceptors that can be created directly or as a reference. Here are a few commonly used built-in interceptors:

  • PaginationInterceptor: Pagination plug-in, supports pagination query for multiple databases.
  • PerformanceAnalyzerInterceptor: Performance analysis plug-in, record the execution time and number of rows affected by each SQL.
  • OptimisticLockerInterceptor: Optimistic lock plug-in to prevent data overwrite problems during concurrent updates.
  • BlockAttackInterceptor: Block malicious attacks on plug-ins to prevent data loss due to batch deletion or update operations.

6. Common application scenarios

  • SQL Logging: As shown above, record the time, parameters and results of each SQL execution, for easy debugging and performance analysis.
  • Pagination plugin: Dynamically add paging conditions to query statements without modifying the original Mapper file.
  • SQL Performance Monitoring: Statistics the number of executions, average time consumption and other indicators of each SQL to help identify potential performance bottlenecks.
  • Cache implementation: Based on the interceptor, simple query result caching is implemented to reduce unnecessary database access.
  • Data desensitization: Encrypt or replace sensitive fields before the query result is returned to ensure data security.
  • Permission control: Check user permissions before SQL execution to prevent unauthorized operations.

7. Best Practices

  • Select the interceptor on demand: Select the appropriate interceptor according to actual needs. If you need to modify SQL statements, parameters or results, you can use InnerInterceptor. If you need to intercept other components of MyBatis, you can use Interceptor.
  • Fine-grained control: The execution scope of InnerInterceptor can be controlled granularly based on the ID of the MappedStatement or the content of the SQL statement.
  • Use the built-in InnerInterceptor: MyBatis Plus provides many built-in InnerInterceptor implementations, such as paging plug-ins, optimistic locking plug-ins, SQL performance analysis plug-ins, etc., which can be used directly without repeated development.
  • Avoid time-consuming operations: InnerInterceptor executes on critical nodes executed by SQL, avoiding time-consuming operations in it to avoid affecting performance.
  • Exception handling: Use the try-catch code block in the InnerInterceptor method to handle possible exceptions to avoid affecting normal business logic.
  • Configuration order: If there are multiple InnerInterceptors, Mybatis Plus will execute according to the order in which the addInnerInterceptor method is called.
  • Using the MyBatis Plus tool class: MyBatis Plus provides some tool classes, such as PluginUtils, which can easily access and modify SQL statements, parameters and other information.

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

  • MyBatisPlus
  • InnerInterceptor

Related Articles

  • How to read properties configuration file in java

    This article mainly introduces the method of java to read properties configuration files, and involves the relevant skills of java to operate properties configuration files. Friends who need it can refer to it
    2015-05-05
  • java snake game writing code

    This article mainly introduces the code writing of Java Snake Game in detail. The sample code in the article is introduced in detail and has certain reference value. Interested friends can refer to it.
    2017-06-06
  • Dynamic proxy (JDK, cglib) instance code in java

    This article mainly introduces dynamic proxy in Java, and here introduces relevant information about JDK dynamic proxy and cglib dynamic proxy
    2017-04-04
  • The problem of the same variable name in Mybatis #foreach causing value overwriting

    This article mainly introduces the problem of the same variable name in Mybatis #foreach that leads to value overlay, which has certain reference value. Interested friends can refer to it.
    2021-07-07
  • Struts2 Static Resource Mapping Code Example

    This article mainly introduces the relevant content of struts2 static resource mapping, involving specific code examples, which have certain reference value. Friends who need it can learn about it.
    2017-09-09
  • Java implements simple mine-sweeping applet

    This article mainly introduces the Java implementation of a simple mine-sweeping mini program. The sample code in the article is introduced in detail and has a certain reference value. Interested friends can refer to it.
    2020-04-04
  • Example of using Swagger2 in Spring Boot project

    This article mainly introduces the example of using Swagger2 in Spring Boot project. The editor thinks it is quite good. Now I will share it with you and give you a reference. Let's take a look with the editor
    2018-01-01
  • Solutions to SpringBoot upload file size restriction problem

    Recently, due to project upgrade, an upload problem was discovered. The following article mainly introduces the solution to the problem of SpringBoot upload file size restriction. The article introduces the example code in detail. Friends who need it can refer to it.
    2022-05-05
  • Example of creating enumeration classes manually in Java

    This article mainly introduces Java to create enumeration classes manually, and analyzes Java’s methods and related operation techniques for creating enumeration classes based on examples. Friends who need it can refer to it
    2019-08-08
  • Detailed explanation of springboot integration of mongodb usage

    MongoDB is a document database (using JSON as the data model) written in C++ language and aims to provide a scalable high-performance data storage solution for WEB applications. This article will introduce you to the detailed introduction of springboot integrated mongodb usage. Friends who need it can refer to it.
    2023-07-07

Latest Comments