MybatisInterceptor使用详解

MybatisInterceptor对需要执行的sql前进行数据处理,例如:
新增时自动添加创建人,创建时间;
更新时自动添加更新人,更新时间。
拦截器原理介绍参考下述大佬博客:
Mybatis拦截器
Mybatis拦截器介绍
mybatis 源码分析(五)Interceptor 详解
@Intercepts-mybatis拦截器
以下对拦截器debug,查看使用过程。

package com.example.demo.config;


import com.example.demo.entity.LoginUser;
import com.example.demo.utils.ConvertUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.binding.MapperMethod.ParamMap;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlCommandType;
import org.apache.ibatis.plugin.*;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;
import java.util.Date;
import java.util.Properties;

/**
 * mybatis拦截器,自动注入创建人、创建时间、修改人、修改时间
 */
@Slf4j
@Component
@Intercepts({@Signature(type = Executor.class, method = "update", args = {MappedStatement.class, Object.class})})
public class MybatisInterceptor implements Interceptor {

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        MappedStatement mappedStatement = (MappedStatement) invocation.getArgs()[0];
        String sqlId = mappedStatement.getId();
        log.debug("------sqlId------" + sqlId);
        SqlCommandType sqlCommandType = mappedStatement.getSqlCommandType();
        Object parameter = invocation.getArgs()[1];
        log.debug("------sqlCommandType------" + sqlCommandType);

        if (parameter == null) {
            return invocation.proceed();
        }
        if (SqlCommandType.INSERT == sqlCommandType) {
            LoginUser sysUser = this.getLoginUser();
            Field[] fields = ConvertUtils.getAllFields(parameter);
            for (Field field : fields) {
                log.debug("------field.name------" + field.getName());
                try {
                    if ("createBy".equals(field.getName())) {
                        field.setAccessible(true);
                        Object local_createBy = field.get(parameter);
                        field.setAccessible(false);
                        if (local_createBy == null || local_createBy.equals("")) {
                            if (sysUser != null) {
                                // 登录人账号
                                field.setAccessible(true);
                                field.set(parameter, sysUser.getUsername());
                                field.setAccessible(false);
                            }
                        }
                    }
                    if ("createByName".equals(field.getName())) {
                        field.setAccessible(true);
                        Object local_createBy = field.get(parameter);
                        field.setAccessible(false);
                        if (local_createBy == null || local_createBy.equals("")) {
                            if (sysUser != null) {
                                // 登录人姓名
                                field.setAccessible(true);
                                field.set(parameter, sysUser.getRealname());
                                field.setAccessible(false);
                            }
                        }
                    }
                    // 注入创建时间
                    if ("createTime".equals(field.getName())) {
                        field.setAccessible(true);
                        Object local_createDate = field.get(parameter);
                        field.setAccessible(false);
                        if (local_createDate == null || local_createDate.equals("")) {
                            field.setAccessible(true);
                            field.set(parameter, new Date());
                            field.setAccessible(false);
                        }
                    }
                    //注入部门编码
                    if ("sysOrgCode".equals(field.getName())) {
                        field.setAccessible(true);
                        Object local_sysOrgCode = field.get(parameter);
                        field.setAccessible(false);
                        if (local_sysOrgCode == null || local_sysOrgCode.equals("")) {
                            // 获取登录用户信息
                            if (sysUser != null) {
                                field.setAccessible(true);
                                field.set(parameter, sysUser.getOrgCode());
                                field.setAccessible(false);
                            }
                        }
                    }
                } catch (Exception e) {
                }
            }
        }
        if (SqlCommandType.UPDATE == sqlCommandType) {
            LoginUser sysUser = this.getLoginUser();
            Field[] fields = null;
            if (parameter instanceof ParamMap) {
                ParamMap<?> p = (ParamMap<?>) parameter;
                //update-begin-author:scott date:20190729 for:批量更新报错issues/IZA3Q--
                if (p.containsKey("et")) {
                    parameter = p.get("et");
                } else {
                    parameter = p.get("param1");
                }
                //update-end-author:scott date:20190729 for:批量更新报错issues/IZA3Q-

                //update-begin-author:scott date:20190729 for:更新指定字段时报错 issues/#516-
                if (parameter == null) {
                    return invocation.proceed();
                }
                //update-end-author:scott date:20190729 for:更新指定字段时报错 issues/#516-

                fields = ConvertUtils.getAllFields(parameter);
            } else {
                fields = ConvertUtils.getAllFields(parameter);
            }

            for (Field field : fields) {
                log.debug("------field.name------" + field.getName());
                try {
                    if ("updateBy".equals(field.getName())) {
                        //获取登录用户信息
                        if (sysUser != null) {
                            // 登录账号
                            field.setAccessible(true);
                            field.set(parameter, sysUser.getUsername());
                            field.setAccessible(false);
                        }
                    }
                    if ("updateByName".equals(field.getName())) {
                        //获取登录用户信息
                        if (sysUser != null) {
                            // 登录账号
                            field.setAccessible(true);
                            field.set(parameter, sysUser.getRealname());
                            field.setAccessible(false);
                        }
                    }
                    if ("updateTime".equals(field.getName())) {
                        field.setAccessible(true);
                        field.set(parameter, new Date());
                        field.setAccessible(false);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        //值注入成功后放行,执行后续步骤
        return invocation.proceed();
    }

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

    @Override
    public void setProperties(Properties properties) {
        // TODO Auto-generated method stub
    }

    private LoginUser getLoginUser() {
        LoginUser loginUser = null;
        try {
            //模拟获取用户信息
            loginUser = new LoginUser();
            loginUser.setId("12345");
            loginUser.setUsername("xiaoming");
            loginUser.setRealname("小明");
            loginUser.setPassword("");
            loginUser.setOrgCode("开发部");
            loginUser.setAvatar("");
            loginUser.setBirthday(new Date());
            loginUser.setSex(1);
            loginUser.setEmail("12345@qq.com");
            loginUser.setPhone("18890908989");
            loginUser.setStatus(1);
        } catch (Exception e) {
            loginUser = null;
        }
        return loginUser;
    }

}

新增操作

在这里插入图片描述
判断当前sql类型是否是insert,遍历所有的入参。判断入参是不是需要自动设置值,然后进行赋值处理
在这里插入图片描述
在这里插入图片描述
createBy,createByName,createTime赋值成功之后执行具体的sql
在这里插入图片描述
sql

INSERT INTO
STUDENT ( id, student_name, age, sex, CREATE_BY, CREATE_BY_NAME, CREATE_TIME, IS_DELETE ) 
VALUES ( 1501370882696634370, '张三', 18, 1, 'xiaoming', '小明', '2022-03-09 09:27:26.719', 0 );

在这里插入图片描述

更新操作

在这里插入图片描述
parameter为
在这里插入图片描述
执行自动赋值后可以看出来invocation中第二个数组中参数已经变了
在这里插入图片描述
sql

UPDATE STUDENT SET student_name='张三', age=27, sex=1, UPDATE_BY='xiaoming', UPDATE_BY_NAME='小明', UPDATE_TIME='2022-03-09 09:58:32.519'
 WHERE id=1501370882696634370;

在这里插入图片描述

案例源码

案例源码

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 5
    评论
Mybatis 的插件机制是其非常重要和有用的功能之一,可以对 Mybatis 的执行过程进行拦截和修改,方便我们实现一些自定义的功能和需求。而 Mybatis 的插件机制是通过 Interceptor 接口和 InterceptorChain 类实现的。 Interceptor 接口是 Mybatis 提供的拦截器接口,其定义了两个方法:intercept 和 plugin。其中 intercept 方法是用来拦截 Mybatis 的执行过程的,而 plugin 方法则是用来生成代理对象的。 InterceptorChain 类则是用来管理 Interceptor 实例的,是一个拦截器链。在 Mybatis 初始化时,会将所有的 Interceptor 实例添加到 InterceptorChain 中,当执行 SQL 时,会按顺序依次调用 InterceptorChain 中的 Interceptor 实例的 intercept 方法进行拦截。 下面我们来看一下如何实现一个自定义的 Interceptor。 首先,我们需要实现 Interceptor 接口,并实现其两个方法。 ```java public class MyInterceptor implements Interceptor{ @Override public Object intercept(Invocation invocation) throws Throwable { // 在这里编写拦截器逻辑 return invocation.proceed(); } @Override public Object plugin(Object target) { // 生成代理对象 return Plugin.wrap(target, this); } } ``` 在 intercept 方法中,我们可以编写一些自定义的拦截逻辑。在最后,一定要调用 invocation.proceed() 方法,否则 Mybatis 的执行过程将会被中止。 在 plugin 方法中,我们需要通过 Plugin.wrap(target, this) 方法生成一个代理对象。这个代理对象将会被添加到 InterceptorChain 中,用于拦截 Mybatis 的执行过程。 接下来,我们需要在 Mybatis 中配置我们的自定义 Interceptor。 ```xml <plugins> <plugin interceptor="com.example.MyInterceptor"/> </plugins> ``` 在配置文件中,我们需要添加一个 plugins 标签,并在其中添加一个 plugin 标签,指定我们的拦截器类的全限定名。 这样,我们就完成了一个简单的自定义 Interceptor 的编写和配置。 总结一下,Mybatis 的插件机制是通过 Interceptor 接口和 InterceptorChain 类实现的。我们可以通过实现 Interceptor 接口来编写自定义的拦截器,并在配置文件中添加相应的配置来启用它。在实现 Interceptor 时,我们需要实现两个方法:intercept 和 plugin。其中 intercept 方法用于编写拦截逻辑,plugin 方法用于生成代理对象。在最后,一定要调用 invocation.proceed() 方法,否则 Mybatis 的执行过程将会被中止。
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值