Mybatis日志打印Sql

配置mybatis-config.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration
    PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
    "http://mybatis.org/dtd/mybatis-3-config.dtd">

<configuration>

    <plugins>
         <plugin interceptor="MybatisInterceptor"></plugin>
    </plugins>
</configuration>

新建JAVA类 MybatisInterceptor

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

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.Plugin;
import org.apache.ibatis.plugin.Signature;
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;  

@Intercepts({
        @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 }) })
public class MybatisInterceptor implements Interceptor {  

    private Properties properties;  

    public Object intercept(Invocation invocation) throws Throwable {
        MappedStatement mappedStatement = (MappedStatement) invocation.getArgs()[0];
        Object parameter = null;
        if (invocation.getArgs().length > 1) {
            parameter = invocation.getArgs()[1];
        }
        String sqlId = mappedStatement.getId();
        BoundSql boundSql = mappedStatement.getBoundSql(parameter);
        Configuration configuration = mappedStatement.getConfiguration();
        Object returnValue = null;
        long start = System.currentTimeMillis();
        returnValue = invocation.proceed();
        long end = System.currentTimeMillis();
        long time = (end - start);
        if (time > 1) {
            String sql = getSql(configuration, boundSql, sqlId, time);
            System.err.println(sql);
        }
        return returnValue;
    }  

    public 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);
        str.append(":");
        str.append(time);
        str.append("ms");
        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(new Date()) + "‘";
        } else {
            if (obj != null) {
                value = obj.toString();
            } else {
                value = "";
            }  

        }
        return value;
    }  

    public static String showSql(Configuration configuration, BoundSql boundSql) {
        Object parameterObject = boundSql.getParameterObject();
        List<ParameterMapping> parameterMappings = boundSql.getParameterMappings();
        String sql = boundSql.getSql().replaceAll("[\\s]+", " ");
        if (parameterMappings.size() > 0 && parameterObject != null) {
            TypeHandlerRegistry typeHandlerRegistry = configuration.getTypeHandlerRegistry();
            if (typeHandlerRegistry.hasTypeHandler(parameterObject.getClass())) {
                sql = sql.replaceFirst("\\?", 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("\\?", getParameterValue(obj));
                    } else if (boundSql.hasAdditionalParameter(propertyName)) {
                        Object obj = boundSql.getAdditionalParameter(propertyName);
                        sql = sql.replaceFirst("\\?", getParameterValue(obj));
                    }
                }
            }
        }
        return sql;
    }  

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

    public void setProperties(Properties properties0) {
        this.properties = properties0;
    }
}  
时间: 2024-10-13 09:09:53

Mybatis日志打印Sql的相关文章

MyBatis 插件 : 打印 SQL 及其执行时间

Plugins 摘一段来自MyBatis官方文档的文字. MyBatis允许你在某一点拦截已映射语句执行的调用.默认情况下,MyBatis允许使用插件来拦截方法调用: Executor(update.query.flushStatements.commint.rollback.getTransaction.close.isClosed) ParameterHandler(getParameterObject.setParameters) ResultSetHandler(handleResult

mybatis配置打印sql

mybatis配置打印sql: <settings> <setting name="logImpl" value="STDOUT_LOGGING"/> </settings> 原文地址:https://www.cnblogs.com/super-chao/p/11474020.html

mybatis 控制台打印sql语句

其实很简单,打印SQL只需要加一个setting就可以了.亲测可用. mybatis-config.xml: <settings>        <setting name="cacheEnabled" value="true" />        <!-- 打印sql日志 -->        <setting name="logImpl" value="STDOUT_LOGGING"

spring-mvc Mybatis插件打印SQL

代码: package com.chainup.exchange.service.adapter; import com.chainup.exchange.service.impl.AccountServiceImpl; import org.apache.ibatis.executor.Executor; import org.apache.ibatis.mapping.BoundSql; import org.apache.ibatis.mapping.MappedStatement; im

mybatis logback打印sql

<?xml version="1.0" encoding="UTF-8" ?><configuration> <contextName>acfun-service.spread-provider</contextName> <!-- 声明变量 --> <substitutionProperty name="log.base" value="./logs/acfun-ser

MyBatis:打印SQL 日志

配置Log4J比较简单, 比如需要记录这个mapper接口的日志: package org.mybatis.example; public interface BlogMapper { @Select("SELECT * FROM blog WHERE id = #{id}") Blog selectBlog(int id); } 只要在应用的classpath中创建一个名称为log4j.properties的文件, 文件的具体内容如下: # Global logging config

springBoot log4j集成的mybatis 控制台打印sql

1.如果mybatis有logback.xml文件,作为优先级会优先选择加载logback.xml文件-->进行sql打印, 在logback.xml文件下加一个配置:具体配置如下:“”直接加一句“” <logger name="org.apache.ibatis" level="DEBUG" /> name:这个 2.clean一下maven,debug启动,sql直接打印在控制台,提示:可以的话添加一个第三方插件,纯sql打印 (mybatis

源码分析之spring-JdbcTemplate日志打印sql语句

对于开源的项目来说的好处就是我们遇到什么问题可以通过看源码来解决. 比如近期有个同事问我说,为啥JdbcTemplate中只有在Error的时候才打印出sql语句呢.我一想,这和log的配置有关系吧. 我们的系统中使用了slf4j作为日志管理工具,之前也好像看到过项目工程中配置的日志级别是error的,所以当代码错误时打印出sql语句应该也属于正常.但是想要正常运行时也打印出sql语句,相比和配置有关,但是应该配置那个级别呢? 应该要看下JdbcTemplate的源码怎么写的,这样可快速定位配置

mybatis log 打印sql 语句

<configuration debug="true">添加一下几行 <logger name="com.ibatis" level="DEBUG" />    <logger name="com.ibatis.common.jdbc.SimpleDataSource" level="DEBUG" />    <logger name="com.ibati