自定义mybatis拦截器拦截sql

配置文件装载拦截器

拦截器代码:
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.ParameterMapping;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Signature;
import org.apache.ibatis.reflection.MetaObject;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.type.TypeHandlerRegistry;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.jdbc.core.JdbcTemplate;

import java.text.DateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.stream.Collectors;

/**
 * 记录更新内容
 */
@Slf4j
@Intercepts({@Signature(type = Executor.class, method = "update", args = {MappedStatement.class,
        Object.class})})
public class MybatisUpdateInterceptor implements Interceptor {

    private static String [] officeIdNames = new String[]{"OFFICE_ID","OFFICEID","PK_OFFICE_ID"};


    @Lazy
    @Autowired
    private SysAuditUpdateLogMapper sysAuditUpdateLogMapper;

    @Override
    public Object intercept(Invocation invocation) throws Throwable {

        Object logId = ThreadLocalUtil.get("logId");
        if(logId != null){
            log.debug("审计日志主键"+logId.toString());
            //解决拦截器执行两次的问题
            String name = invocation.getTarget().getClass().getName();
            if(!"org.apache.ibatis.executor.CachingExecutor".equals(name)){
                MappedStatement mappedStatement = (MappedStatement)invocation.getArgs()[0];
                //0.sql参数获取
                Object parameter = null;
                if (invocation.getArgs().length > 1) {
                    parameter = invocation.getArgs()[1];
                }
                //1.获取sqlId
                String sqlId = mappedStatement.getId();
                BoundSql boundSql = mappedStatement.getBoundSql(parameter);

                Configuration configuration = mappedStatement.getConfiguration();
                //获取真实的sql语句
                String sql = getSql(configuration, boundSql, sqlId, 0);

                if(!sql.contains("INSERT")){
                    //2.判断是否有officeId
                    if (hasOfficeId(sql,officeIdNames)) {
                        log.warn("{}", sql);
                    } else {
                        log.debug("{}", sql);
                    }

                    //截取表名
                    String tableName = sql.substring(sql.indexOf("UPDATE") + 6, sql.indexOf("SET"));
                    //截取where条件
                    String where = sql.substring(sql.indexOf("WHERE"));
                    String selectSql = "SELECT * FROM " + tableName + where;
                    log.debug(selectSql);
                    List<Map<String, Object>> maps = sysAuditUpdateLogMapper.queryForList(selectSql);
                    //截取出要更新的参数
                    String paras = sql.substring(sql.indexOf("SET") + 3, sql.indexOf("WHERE"));
                    paras = paras.replace("=", ":");
                    JSONObject jsonObject = JSONObject.parseObject("{" + paras + "}");
                    log.debug(jsonObject.toString());
                    log.debug(maps.toString());
                    //查询表注释
                    List<Map<String, Object>> colMap = sysAuditUpdateLogMapper.queryForComment(tableName.trim());
                    Map<Object,Object> columnName = new HashMap<>();
                    colMap.forEach(a->{
                        columnName.put(a.get("COLUMN_NAME"),a.get("COLUMN_COMMENT"));
                    });

                    //比对是否跟新
                    for (Map<String, Object> stringObjectMap : maps){
                        //所修改内容描述
                        StringBuffer desc = new StringBuffer();
                        //变更的所有值
                        StringBuffer buffer = new StringBuffer("{" );
                        for(Map.Entry entry :jsonObject.entrySet()){
                            for(Map.Entry entry2 :stringObjectMap.entrySet()){
                                if(entry.getKey().equals(entry2.getKey())){
                                    if(!entry.getValue().equals(entry2.getValue())){
                                        buffer.append(entry.getKey() + ":" +entry.getValue() +",");
                                        desc.append(Objects.isNull(columnName.get(entry.getKey()))? entry.getKey(): columnName.get(entry.getKey()))
                                                .append(" 由 ").append(entry2.getValue()).append(" 修改为 ")
                                                .append(entry.getValue()).append(",");
                                    }
                                }
                            }
                        }

                        log.debug(buffer.toString());
                    }
                }
            }
        }

        return invocation.proceed();
    }

    /**
     * 判断sql语句中是否包含officeId字段
     *
     * @param sql sql语句
     * @return
     */
    private boolean hasOfficeId(String sql,String[] officeIdNames) {
        //office ID 的可能名称
        if (sql == null || sql.trim().length() == 0) {
            return false;
        }
        String afterWhereStatement = sql.toUpperCase().substring(sql.indexOf("WHERE"));

        for (String officeIdName : officeIdNames){
            if(afterWhereStatement.indexOf(officeIdName) > 0){
                return true;
            }
        }
        return false;
    }

    private static String getSql(Configuration configuration, BoundSql boundSql,
                                 String sqlId, long time) {
        String sql = showSql(configuration, boundSql);
        StringBuilder str = new StringBuilder(100);
//        str.append(sqlId);
//        str.append(":");
        str.append(sql);
        return str.toString();
    }

    private static String getParameterValue(Object obj) {
        String value = null;
        if (obj instanceof String) {
            value = "'" + obj.toString() + "'";
        } else if (obj instanceof Date) {
            DateFormat formatter = DateFormat.getDateTimeInstance(
                    DateFormat.DEFAULT, DateFormat.DEFAULT, Locale.CHINA);
            value = "'" + formatter.format(obj) + "'";
        } else {
            if (obj != null) {
                value = obj.toString();
            } else {
                value = "";
            }

        }
        return value;
    }

    private static String showSql(Configuration configuration, BoundSql boundSql) {
        Object parameterObject = boundSql.getParameterObject();
        List<ParameterMapping> parameterMappings = boundSql.getParameterMappings();
        String sql = boundSql.getSql().replaceAll("[\\s]+", " ");
        if (!parameterMappings.isEmpty() && parameterObject != null) {
            TypeHandlerRegistry typeHandlerRegistry = configuration
                    .getTypeHandlerRegistry();
            if (typeHandlerRegistry.hasTypeHandler(parameterObject.getClass())) {
                sql = sql.replaceFirst("\\?",
                        Matcher.quoteReplacement(getParameterValue(parameterObject)));

            } else {
                MetaObject metaObject = configuration
                        .newMetaObject(parameterObject);
                for (ParameterMapping parameterMapping : parameterMappings) {
                    String propertyName = parameterMapping.getProperty();
                    if (metaObject.hasGetter(propertyName)) {
                        Object obj = metaObject.getValue(propertyName);
                        sql = sql.replaceFirst("\\?", Matcher.quoteReplacement(getParameterValue(obj)));
                    } else if (boundSql.hasAdditionalParameter(propertyName)) {
                        Object obj = boundSql
                                .getAdditionalParameter(propertyName);
                        sql = sql.replaceFirst("\\?", Matcher.quoteReplacement(getParameterValue(obj)));
                    } else {
                        sql = sql.replaceFirst("\\?", "缺失");
                    }//打印出缺失,提醒该参数缺失并防止错位
                }
            }
        }
        return sql;
    }

}

 注意:注入的时候加上@Lazy注解,不然回报循环引用

### 创建和使用 MyBatis 自定义 SQL 拦截器 #### 实现原理 MyBatis 提供了插件机制来允许开发者创建自定义拦截器。这些拦截器可以用于拦截执行器(Executor)、参数处理(ParameterHandler)、结果集处理(ResultHandler)以及语句处理器(StatementHandler)[^1]。 为了实现一个自定义拦截器,需要编写一个类并使其继承 `Interceptor` 接口,在该接口中重写 `intercept()` 方法以加入想要执行的额外逻辑。此外还需要配置此拦截器以便它能够被 MyBatis 使用。 #### 示例代码 下面是一个简单的例子展示如何创建一个日志记录拦截器: ```java import org.apache.ibatis.executor.statement.StatementHandler; import org.apache.ibatis.plugin.*; import java.sql.Statement; import java.util.Properties; @Intercepts({ @Signature(type = StatementHandler.class, method = "prepare", args = {Connection.class, Integer.class}) }) public class LoggingInterceptor implements Interceptor { public Object intercept(Invocation invocation) throws Throwable { System.out.println("Before preparing statement..."); try { Object result = invocation.proceed(); System.out.println("After preparing statement."); return result; } catch (Throwable t) { System.err.println("Error while preparing statement: " + t.getMessage()); throw t; } } public Object plugin(Object target) { return Plugin.wrap(target, this); } public void setProperties(Properties properties) {} } ``` 这段代码展示了如何通过覆盖 `intercept()` 函数来自定义行为,并利用 `plugin()` 和 `setProperties()` 来完成必要的初始化工作。 要使这个拦截器生效,则需将其注册到 MyBatis 配置文件中的 `<plugins>` 节点下: ```xml <configuration> <!-- ... --> <plugins> <plugin interceptor="com.example.LoggingInterceptor"/> </plugins> <!-- ... --> </configuration> ``` 以上就是关于在 MyBatis 中创建和使用自定义 SQL 拦截器的方法介绍及其背后的实现原理说明。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值