mybatis拦截器打印sql日志

前言

利用mybatis拦截器打印输出sql

操作

  1. 编写拦截器
java 复制代码
package com.it2.excel01.interceptor;

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

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.dbcp2.BasicDataSource;
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})})
@Slf4j
public class SqlLogInterceptor implements Interceptor {
    @Override
    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];
        }

        BoundSql boundSql = mappedStatement.getBoundSql(parameter);
        Configuration configuration = mappedStatement.getConfiguration();

        Object returnValue = null;
        //获取sql语句
        String sql = showSql(configuration, boundSql);
        //获取数据源
        BasicDataSource db = (BasicDataSource) configuration.getEnvironment().getDataSource();

        long s = System.currentTimeMillis();
        //执行结果
        returnValue = invocation.proceed();
        long e = System.currentTimeMillis();
        log.info("执行时间:{} ms,数据源:{},sql:{}", (e - s), db.getUrl(), sql);
        return returnValue;
    }

    @Override
    public Object plugin(Object target) {
        // TODO Auto-generated method stub
        return Plugin.wrap(target, this);
    }

    @Override
    public void setProperties(Properties properties) {
        // TODO Auto-generated method stub
    }


    private 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;
    }

    public String showSql(Configuration configuration, BoundSql boundSql) {
        Object parameterObject = boundSql.getParameterObject();
        List<ParameterMapping> parameterMappings = boundSql.getParameterMappings();
        String sql = boundSql.getSql().replaceAll("(?m)^[ \t]*\r?\n", "");//替换空行
        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;
    }
}
  1. 配置拦截器
xml 复制代码
<!-- MyBatis配置 -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <!-- 注意其他配置 -->
        <property name="plugins">
            <array>
                <bean class="com.github.pagehelper.PageInterceptor">
                    <property name="properties">
                        <!--使用下面的方式配置参数,一行配置一个 -->
                        <value>
                            params=value1
                        </value>
                    </property>
                </bean>
                <!--配置拦截-->
                <bean class="com.it2.excel01.interceptor.SqlLogInterceptor">
                </bean>
            </array>
        </property>
    </bean>

PageInterceptor是分页拦截器,此demo中无用,可以去除

相关推荐
蓝桉80220 分钟前
图片爬取案例
开发语言·数据库·python
wang_yb29 分钟前
『Python底层原理』--Python整数为什么可以无限大
python·databook
敲上瘾36 分钟前
基础dp——动态规划
java·数据结构·c++·python·算法·线性回归·动态规划
Dawndddddd42 分钟前
网络安全之攻防笔记--通用安全漏洞SQL注入&sqlmap&Oracle&mongodb&DB2
笔记·sql·安全·web安全
阑梦清川1 小时前
Jupyter里面的manim编程学习
python·jupyter·manim
Dongwoo Jeong1 小时前
类型系统下的语言分类与类型系统基础
java·笔记·python·lisp·fortran·type
偏右右1 小时前
UNION 联合查询
数据库·sql
enyp802 小时前
*PyCharm 安装教程
ide·python·pycharm
哥是黑大帅2 小时前
Docker基于Ollama本地部署大语言模型
python·docker·语言模型
代码的乐趣2 小时前
支持selenium的chrome driver更新到133.0.6943.126
chrome·python·selenium