mybatis增加日志打印插件

可以在分页插件PageHelperAutoConfiguration注入的时候,注入日志打印插件

java 复制代码
public void afterPropertiesSet() {
    PageInterceptor interceptor = new PageInterceptor(this.helperProperties);
    interceptor.setProperties(this.helperProperties.getProperties());
    for (SqlSessionFactory sqlSessionFactory : sqlSessionFactoryList) {
        org.apache.ibatis.session.Configuration configuration = sqlSessionFactory.getConfiguration();
        if (!containsInterceptor(configuration, interceptor)) {
            logger.warn("加载分页插件");
            configuration.addInterceptor(interceptor);
        }
        //日志插件
         configuration.addInterceptor(new SqlLoggingInterceptor());
    }
}

SqlLoggingInterceptor类

java 复制代码
package com.dd.oss.common.datasource.mybatis;

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 java.text.DateFormat;
import java.util.*;
import java.util.regex.Matcher;

@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 SqlLoggingInterceptor implements Interceptor {

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        Object[] args = invocation.getArgs();
        try {
            if (args != null && args.length > 1) {
                MappedStatement mappedStatement = (MappedStatement) args[0];
                Object parameter = args[1];
                BoundSql boundSql = mappedStatement.getBoundSql(parameter);
                Configuration configuration = mappedStatement.getConfiguration();
                //
                // 得到sql语句
                String sql = showSql(configuration, boundSql);
                System.out.println("SQL语句:" + sql);
            }
        } catch (Exception e) {
            System.out.println("SQL语句异常");
        }
        return invocation.proceed();
    }

    /**
     * 解析sql语句
     */
    protected 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("\\?", Matcher.quoteReplacement(getParameterValue(parameterObject)));
            } else {
                String tmpSql = sql.replaceAll("\\?", "%s");
                String[] params = new String[parameterMappings.size()];
                MetaObject metaObject = configuration.newMetaObject(parameterObject);
                int i = 0;
                for (ParameterMapping parameterMapping : parameterMappings) {
                    String propertyName = parameterMapping.getProperty();
                    if (metaObject.hasGetter(propertyName)) {
                        Object obj = metaObject.getValue(propertyName);
                        params[i++] = Matcher.quoteReplacement(getParameterValue(obj));
                    } else if (boundSql.hasAdditionalParameter(propertyName)) {
                        Object obj = boundSql.getAdditionalParameter(propertyName);
                        params[i++] = Matcher.quoteReplacement(getParameterValue(obj));
                    }
                }
                sql = String.format(tmpSql, params);
            }
        }
        return sql;
    }

    /**
     * 参数解析
     */
    protected String getParameterValue(Object obj) {
        String value;
        if (obj instanceof String) {
            value = "'" + obj + "'";
        } 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;
    }
}
相关推荐
秋恬意3 小时前
Mybatis能执行一对一、一对多的关联查询吗?都有哪些实现方式,以及它们之间的区别
java·数据库·mybatis
张铁铁是个小胖子13 小时前
MyBatis学习
java·学习·mybatis
hanbarger17 小时前
mybatis框架——缓存,分页
java·spring·mybatis
乘风御浪云帆之上1 天前
数据库操作【JDBC & HIbernate & Mybatis】
数据库·mybatis·jdbc·hibernate
向阳12182 天前
mybatis 动态 SQL
数据库·sql·mybatis
新手小袁_J2 天前
JDK11下载安装和配置超详细过程
java·spring cloud·jdk·maven·mybatis·jdk11
xlsw_2 天前
java全栈day20--Web后端实战(Mybatis基础2)
java·开发语言·mybatis
cmdch20172 天前
Mybatis加密解密查询操作(sql前),where要传入加密后的字段时遇到的问题
数据库·sql·mybatis
秋恬意3 天前
什么是MyBatis
mybatis
CodeChampion3 天前
60.基于SSM的个人网站的设计与实现(项目 + 论文)
java·vue.js·mysql·spring·elementui·node.js·mybatis