idea 打印完整的Sql语句带参数

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了idea 打印完整的Sql语句带参数相关的知识,希望对你有一定的参考价值。

参考技术A 一、插件的安装
首先打开IDEA设置,找到我们的Plugins插件选项,在插件库中搜索插件【Mybatis Log Plugin】选择安装

接着重启开发工具

二、插件的使用
Tools菜单栏下找到Mybatis Log Plugin选项单击

紧接着控制台多了个选项卡,就可以看完整的参数了

Mybatis拦截器实现带参数SQL语句打印

前言

在我们工作实际项目中,常常遇到使用Mybatis作为ORM框架,在使用的过程中,一般都会开启日志的打印功能,这样在控制台就会输出执行的SQL,定位SQL问题也是比较方便的。
但是,我们就会发现,这样打印出来的SQL是预编译语句和参数是分开的。
此时如果需要去数据库执行上条SQL的时候,我们需要手动的把参数拼接到SQL语句中;
参数少此操作还可以,参数一旦比较多,此操作相当的麻烦繁琐。
下面我们就使用Mybatis拦截器的方式来实现打印完整SQL的功能。

具体实现

实现拦截器逻辑

import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.cache.CacheKey;
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.*;
import org.apache.ibatis.reflection.MetaObject;
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.util.CollectionUtils;

import java.text.DateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.Properties;
import java.util.regex.Matcher;

/**
 * @author 公众号: SimpleMemory
 * @version 1.0.0
 * @ClassName FullSQLInterceptor.java
 * @Description TODO
 * @createTime 2022年10月14日 18:39:00
 */
@Slf4j
@Intercepts(value = 
        @Signature(type = Executor.class, method = "update", args = MappedStatement.class, Object.class),
        @Signature(type = Executor.class, method = "query", args = MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class, CacheKey.class, BoundSql.class),
        @Signature(type = Executor.class, method = "query", args = MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class))
public class MybatisSQLInterceptor implements Interceptor 

    @Override
    public Object intercept(Invocation invocation) throws Throwable 
        try 
            // 获取xml中的一个select/update/insert/delete节点,主要描述的是一条SQL语句
            MappedStatement mappedStatement = (MappedStatement) invocation.getArgs()[0];
            Object parameter = null;
            // 获取参数,if语句成立,表示sql语句有参数,参数格式是map形式
            if (invocation.getArgs().length > 1) 
                parameter = invocation.getArgs()[1];
                log.error("sql-param:", parameter);
            
           /* if (SqlCommandType.SELECT.equals(mappedStatement.getSqlCommandType())) 
            */
            // 获取到节点的id,即sql语句的id
            String sqlId = mappedStatement.getId();
            // BoundSql就是封装myBatis最终产生的sql类
            BoundSql boundSql = mappedStatement.getBoundSql(parameter);
            // 获取节点的配置
            Configuration configuration = mappedStatement.getConfiguration();
            // 获取到最终的sql语句
            String sql = getSql(configuration, boundSql, sqlId);
            log.error("sql->", sql);
         catch (Exception e) 
        
        // 执行完上面的任务后,不改变原有的sql执行过程
        return invocation.proceed();
    

    /**
     * 封装了一下sql语句,使得结果返回完整xml路径下的sql语句节点id + sql语句
     *
     * @param configuration configuration
     * @param boundSql      boundSql
     * @param sqlId         sqlId
     * @return java.lang.String
     */
    public static String getSql(Configuration configuration, BoundSql boundSql, String sqlId) 
        String sql = showSql(configuration, boundSql);
        StringBuilder str = new StringBuilder(100);
        str.append(sqlId);
        str.append(":");
        str.append(sql);
        return str.toString();
    

    /**
     * 如果参数是String,则添加单引号, 如果是日期,则转换为时间格式器并加单引号;
     * 对参数是null和不是null的情况作了处理
     *
     * @param obj obj
     * @return java.lang.String
     */
    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(new Date()) + "'";
         else 
            if (obj != null) 
                value = obj.toString();
             else 
                value = "";
            

        
        return value;
    

    /**
     * 进行?的替换
     *
     * @param configuration
     * @param boundSql
     * @return
     */
    public static String showSql(Configuration configuration, BoundSql boundSql) 
        Object parameterObject = boundSql.getParameterObject();  // 获取参数
        List<ParameterMapping> parameterMappings = boundSql
                .getParameterMappings();
        String sql = boundSql.getSql().replaceAll("[\\\\s]+", " ");  // sql语句中多个空格都用一个空格代替
        if (!CollectionUtils.isEmpty(parameterMappings) && parameterObject != null) 
            TypeHandlerRegistry typeHandlerRegistry = configuration.getTypeHandlerRegistry(); // 获取类型处理器注册器,类型处理器的功能是进行java类型和数据库类型的转换<br>// 如果根据parameterObject.getClass()可以找到对应的类型,则替换
            if (typeHandlerRegistry.hasTypeHandler(parameterObject.getClass())) 
                sql = sql.replaceFirst("\\\\?", Matcher.quoteReplacement(getParameterValue(parameterObject)));

             else 
                MetaObject metaObject = configuration.newMetaObject(parameterObject);// MetaObject主要是封装了originalObject对象,提供了get和set的方法用于获取和设置originalObject的属性值,主要支持对JavaBean、Collection、Map三种类型对象的操作
                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 = sql.replaceFirst("\\\\?", Matcher.quoteReplacement(getParameterValue(obj)));
                     else 
                        sql = sql.replaceFirst("\\\\?", "缺失");
                    //打印出缺失,提醒该参数缺失并防止错位
                
            
        
        return sql;
    

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

    @Override
    public void setProperties(Properties properties) 

    


配置拦截器

在Mybatis的配置文件中配置拦截器

<plugins>
      <plugin interceptor="com.ruoyi.web.config.MybatisSQLInterceptor"></plugin>
</plugins>

在application.yml中配置Mybatis的全局的配置文件mybatis-config.xml

实现效果

启动项目,查看控制台打印SQL语句情况。

2022-10-15 09:51:50.780 ERROR 30292 --- [io-8089-exec-24] c.r.web.config.MybatisSQLInterceptor     : sql->com.ruoyi.system.mapper.SysDeptMapper.selectDeptList:select d.dept_id, d.parent_id, d.ancestors, d.dept_name, d.order_num, d.leader, d.phone, d.email, d.status, d.del_flag, d.create_by, d.create_time from sys_dept d where d.del_flag = '0' AND dept_name like concat('%', '开发', '%') AND status = '0' order by d.parent_id, d.order_num

以上是关于idea 打印完整的Sql语句带参数的主要内容,如果未能解决你的问题,请参考以下文章

Mybatis拦截器实现带参数SQL语句打印

Mybatis拦截器实现带参数SQL语句打印

IDEA集成Mybatis打印日志插件

mybatis-plus打印完整sql语句

mybatis-plus打印完整sql语句

mybatis-plus打印完整sql语句