MyBatis 插件之拦截器(Interceptor)

Posted 好记性不如烂笔头=》

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了MyBatis 插件之拦截器(Interceptor)相关的知识,希望对你有一定的参考价值。

参考 https://blog.csdn.net/weixin_39494923/article/details/91534658

//项目实际使用

package com.yueworldframework.core.mybatis;

import com.yueworldframework.core.support.SessionHelper;
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.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;

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

/**
 * Created by wangbs
 */
@Intercepts({@Signature(type = Executor.class, method = "update", args = {MappedStatement.class, Object.class})})
public class AuditingInterceptor implements Interceptor {
    private static final Logger logger = LoggerFactory.getLogger(AuditingInterceptor.class);

    private Properties props = null;

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        MappedStatement mappedStatement = (MappedStatement) invocation.getArgs()[0];
        SqlCommandType sqlCommandType = mappedStatement.getSqlCommandType();
        if (invocation.getArgs()[1] instanceof Pojo) {
            Pojo parameter = (Pojo) invocation.getArgs()[1];
            if (SqlCommandType.INSERT == sqlCommandType) {
                // 初始化主键ID
                Method initializeUUID = BeanUtils.findDeclaredMethod(parameter.getClass(), "initializeUUID");
                if (null != initializeUUID) {
                    initializeUUID.invoke(parameter);
                }
                if(null==parameter.getCreator()){
                    parameter.setCreator(SessionHelper.getId());
                }
                parameter.setUpdater(SessionHelper.getId());
                parameter.setCreatedDate(new Date());
                parameter.setUpdatedDate(parameter.getCreatedDate());
                parameter.setVersion(1);
            } else if (SqlCommandType.UPDATE == sqlCommandType) {
                parameter.setUpdater(SessionHelper.getId());
                parameter.setUpdatedDate(new Date());
                parameter.setVersion(parameter.getVersion() + 1);
            }
        }
        return invocation.proceed();
    }

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

    public void setProperties(Properties properties) {
        if (null != properties && !properties.isEmpty()) props = properties;
    }
}

  

以上是关于MyBatis 插件之拦截器(Interceptor)的主要内容,如果未能解决你的问题,请参考以下文章

MyBatis 插件之拦截器(Interceptor)

深入浅出Mybatis之拦截器

182. Spring Boot MyBatis插件之拦截器(Interceptor)实现原理

精通Mybatis之插件体系(与中间件实现的一些思考)

精通Mybatis之插件体系(与中间件实现的一些思考)

MyBatis之简单了解Plugin