Basic usage of MyBatis - custom interception rules

First of all, the MyBatis-Plus framework is an open source framework based on MyBatis for functional expansion, which provides many convenient functions for operating databases.

In MyBatis-Plus, you can intercept and modify SQL statements through custom interceptors. Here is an example of custom interceptor using MyBatis-Plus:

  1. Create a custom interceptor class, inherit com.baomidou.mybatisplus.extension.plugins.inner.InnerInterceptorthe class, and implement the methods in it. For example, we create a MyInterceptorclass:
import com.baomidou.mybatisplus.extension.plugins.inner.InnerInterceptor;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.plugin.*;

import java.util.Properties;

@Intercepts({
    
    @Signature(type = Executor.class, method = "update", args = {
    
    MappedStatement.class, Object.class})})
public class MyInterceptor implements InnerInterceptor {
    
    

    @Override
    public void beforeUpdate(MetaObject metaObject, MappedStatement ms, Object parameter) {
    
    
        // 在update操作执行之前拦截处理
        System.out.println("beforeUpdate");
    }

    @Override
    public void afterUpdate(MetaObject metaObject, MappedStatement ms, Object parameter) {
    
    
        // 在update操作执行之后拦截处理
        System.out.println("afterUpdate");
    }

    @Override
    public void setProperties(Properties properties) {
    
    
        // 设置拦截器的配置参数
    }
}
  1. Configure MyBatis-Plus to use custom interceptors. Add the following configuration in application.properties(or application.yml) file:
# 启用MyBatis-Plus
mybatis-plus.enabled=true

# 配置自定义拦截器
mybatis-plus.configuration.intercepts=com.example.MyInterceptor
  1. Add annotations to @Mapperthe corresponding Mapper class of the interface @Interceptsto specify the method to be intercepted. For example:
@Mapper
@Intercepts({
    
    @Signature(type = Executor.class, method = "update", args = {
    
    MappedStatement.class, Object.class})})
public interface UserMapper extends BaseMapper<User> {
    
    

}

The above are the basic steps to use MyBatis-Plus to customize the interceptor. By inheriting InnerInterceptorthe interface and rewriting the corresponding method, the interception and modification of the SQL statement can be realized. After the interceptor is configured, the method of the interceptor will be called every time the corresponding database operation is performed.

It should be noted that MyInterceptorthe class in the above example is just a simple example, and needs to be customized according to specific needs in actual use.

Reference documents:

Guess you like

Origin blog.csdn.net/qq_41177135/article/details/131813019