mybatis(mybatis-plus)使用sql攔截器和自定義注解獲取sql和參數


 注解 SqlLogs

package com.ruoyi.common.annotation;

import java.lang.annotation.*;

/**
 * 獲取sql注解
 *
 * @author ruoyi
 */
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface SqlLogs
{
    /**
     * 是否打印sql
     */
    public boolean hasSqlLog() default false;



}

 sql攔截器 SqlLogsInterceptor 

package com.ruoyi.framework.config;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.PluginUtils;
import com.baomidou.mybatisplus.extension.handlers.AbstractSqlParserHandler;

import com.ruoyi.common.annotation.SqlLogs;

import com.baomidou.mybatisplus.core.toolkit.PluginUtils;
import com.baomidou.mybatisplus.extension.handlers.AbstractSqlParserHandler;
import com.ruoyi.common.annotation.SqlLogs;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.executor.statement.StatementHandler;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.ParameterMapping;
import org.apache.ibatis.mapping.SqlCommandType;
import org.apache.ibatis.plugin.*;
import org.apache.ibatis.reflection.MetaObject;
import org.apache.ibatis.reflection.SystemMetaObject;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;
import org.apache.ibatis.type.TypeHandlerRegistry;
import org.springframework.stereotype.Component;
import javax.sql.DataSource;
import java.lang.reflect.Method;
import java.sql.Connection;
import java.text.DateFormat;
import java.util.*;
import java.util.concurrent.locks.StampedLock;


@Slf4j
@AllArgsConstructor
//@Aspect
@Intercepts({
        @Signature(type = Executor.class, method = "query", args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class}),
        @Signature(type = StatementHandler.class, method = "prepare", args = {Connection.class, Integer.class})
})
@Component
public class SqlLogsInterceptor extends AbstractSqlParserHandler implements Interceptor {

    private DataSource dataSource;

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        Map<String,Object> sqlMap = new HashMap<>();
        Boolean hasSqlLogs = false;
        StatementHandler statementHandler = PluginUtils.realTarget(invocation.getTarget());
        MetaObject metaObject = SystemMetaObject.forObject(statementHandler);
        this.sqlParser(metaObject);
        // 先判斷是不是SELECT操作 不是直接過濾
        MappedStatement mappedStatement =
                (MappedStatement) metaObject.getValue("delegate.mappedStatement");
        if (!SqlCommandType.SELECT.equals(mappedStatement.getSqlCommandType())) {
            return invocation.proceed();
        }

        final Object[] args = invocation.getArgs();
        //獲取執行方法的位置
        String namespace = mappedStatement.getId();
        //獲取mapper名稱
        String className = namespace.substring(0,namespace.lastIndexOf("."));
        //獲取方法名
        String methedName= namespace.substring(namespace.lastIndexOf(".") + 1,namespace.length());
        //獲取當前mapper 的方法
        Method[] ms = Class.forName(className).getMethods();
        for(Method m : ms){
            if(m.getName().equals(methedName)){
          //獲取注解  來判斷是不是要儲存sql
                SqlLogs annotation = m.getAnnotation(SqlLogs.class);
                if(annotation != null){
                    hasSqlLogs = annotation.hasSqlLog();
                }
            }
        }
        //如果是有注解值為true,便獲取sql處理參數
        if(hasSqlLogs){
            BoundSql boundSql = (BoundSql) metaObject.getValue("delegate.boundSql");
            // 執行的SQL語句
            String originalSql = boundSql.getSql();
            // SQL語句的參數
            Object parameterObject = boundSql.getParameterObject();
            if(parameterObject != null){
                originalSql = showSql(configuration, boundSql);
            }
            System.err.println("sql :"+originalSql);
        }
        return invocation.proceed();

    }

    /**
     * 生成攔截對象的代理
     *
     * @param target 目標對象
     * @return 代理對象
     */
    @Override
    public Object plugin(Object target) {
        if (target instanceof StatementHandler) {
            return Plugin.wrap(target, this);
        }
        return target;
    }

    /**
     * 獲取參數值
     * @param obj
     * @return
     */
    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 = "to_date('" + formatter.format(obj) + "','yyyy-MM-dd hh24:mi:ss')";
        } else {
            if (obj != null) {
                value = obj.toString();
            } else {
                value = "";
            }

        }
        System.err.println("獲取值: "+value);
        return value;
    }

    /***
     * sql 參數替換
     * @param configuration
     * @param boundSql
     * @return
     */
    public static String showSql(Configuration configuration, BoundSql boundSql) {
        //獲取參數對象
        Object parameterObject = boundSql.getParameterObject();
        //獲取當前的sql語句有綁定的所有parameterMapping屬性
        List<ParameterMapping> parameterMappings = boundSql.getParameterMappings();
        //去除空格
        String sql = boundSql.getSql().replaceAll("[\\s]+", " ");
        if (parameterMappings.size() > 0 && parameterObject != null) {
            TypeHandlerRegistry typeHandlerRegistry = configuration.getTypeHandlerRegistry();
            /* 如果參數滿足:org.apache.ibatis.type.TypeHandlerRegistry#hasTypeHandler(java.lang.Class<?>)
            org.apache.ibatis.type.TypeHandlerRegistry#TYPE_HANDLER_MAP
            * 即是不是屬於注冊類型(TYPE_HANDLER_MAP...等/有沒有相應的類型處理器)
             * */
            if (typeHandlerRegistry.hasTypeHandler(parameterObject.getClass())) {
                sql = sql.replaceFirst("\\?", getParameterValue(parameterObject));
            } else {
                //裝飾器,可直接操作屬性值 ---》 以parameterObject創建裝飾器
                //MetaObject 是 Mybatis 反射工具類,通過 MetaObject 獲取和設置對象的屬性值
                MetaObject metaObject = configuration.newMetaObject(parameterObject);
                //循環 parameterMappings 所有屬性
                for (ParameterMapping parameterMapping : parameterMappings) {
                    //獲取property屬性
                    String propertyName = parameterMapping.getProperty();
                    System.err.println("propertyName: "+propertyName);
                    //是否聲明了propertyName的屬性和get方法
                    if (metaObject.hasGetter(propertyName)) {
                        Object obj = metaObject.getValue(propertyName);
                        sql = sql.replaceFirst("\\?", getParameterValue(obj));
                    } else if (boundSql.hasAdditionalParameter(propertyName)) {
                        //判斷是不是sql的附加參數
                        Object obj = boundSql.getAdditionalParameter(propertyName);
                        sql = sql.replaceFirst("\\?", getParameterValue(obj));
                    }
                }
            }
        }
        return sql;
    }

}

  

 在MybatisPlusConfig中注冊bean

    @Bean
    @ConditionalOnMissingBean //有此實例便不進行注冊
    public SqlLogsInterceptor dataScopeInterceptor(DataSource dataSource) {
        return new SqlLogsInterceptor(dataSource);
    }

 

 在mapper中使用注解

    @SqlLogs(hasSqlLog = true)
    List<XgYyxxVo> selectByLqw(@Param(Constants.WRAPPER) Wrapper queryWrapper);

 效果


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM