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;
    }
}
相关推荐
程序猿熊跃晖1 天前
解决 MyBatis-Plus 中 `update.setProcInsId(null)` 不生效的问题
数据库·tomcat·mybatis
Hars、Wlgb1 天前
mybatis 自带的几个插入接口的区别
mybatis
XiaoLeisj1 天前
【MyBatis】深入解析 MyBatis XML 开发:增删改查操作和方法命名规范、@Param 重命名参数、XML 返回自增主键方法
xml·java·数据库·spring boot·sql·intellij-idea·mybatis
KATA~2 天前
解决MyBatis-Plus枚举映射错误:No enum constant问题
java·数据库·mybatis
伊成2 天前
Springboot整合Mybatis+Maven+Thymeleaf学生成绩管理系统
java·maven·mybatis·springboot·学生成绩管理系统
我要学编程(ಥ_ಥ)2 天前
初始JavaEE篇 —— Mybatis-plus 操作数据库
java·java-ee·mybatis·mybatis-plus
〆、风神2 天前
装饰器模式与模板方法模式实现MyBatis-Plus QueryWrapper 扩展
mybatis·装饰器模式·模板方法模式
依旧很淡定3 天前
09-SpringBoot3入门-整合Mybatis
mybatis
Alt.93 天前
MyBatis基础五(动态SQL,缓存)
java·sql·mybatis
okok__TXF3 天前
Mybatis源码分析
java·后端·mybatis