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;
    }
}
相关推荐
弗拉唐7 小时前
springBoot,mp,ssm整合案例
java·spring boot·mybatis
凌冰_9 小时前
IDEA2023 SpringBoot整合MyBatis(三)
spring boot·后端·mybatis
Elaine20239110 小时前
零碎04 MybatisPlus自定义模版生成代码
java·spring·mybatis
一二小选手11 小时前
【MyBatis】全局配置文件—mybatis.xml 创建xml模板
xml·java·mybatis
刘大浪12 小时前
后端数据增删改查基于Springboot+mybatis mysql 时间根据当时时间自动填充,数据库连接查询不一致,mysql数据库连接不好用
数据库·spring boot·mybatis
蓝染-惣右介13 小时前
【MyBatisPlus·最新教程】包含多个改造案例,常用注解、条件构造器、代码生成、静态工具、类型处理器、分页插件、自动填充字段
java·数据库·tomcat·mybatis
武子康14 小时前
Java-07 深入浅出 MyBatis - 一对多模型 SqlMapConfig 与 Mapper 详细讲解测试
java·开发语言·数据库·sql·mybatis·springboot
一二小选手14 小时前
【Mybatis】@Param注解 resultMap手动映射
java·mybatis
郑祎亦17 小时前
Spring Boot 项目 myblog 整理
spring boot·后端·java-ee·maven·mybatis