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;
    }
}
相关推荐
鹿屿二向箔13 小时前
基于SSM(Spring + Spring MVC + MyBatis)框架的汽车租赁共享平台系统
spring·mvc·mybatis
沐雪架构师16 小时前
mybatis连接PGSQL中对于json和jsonb的处理
json·mybatis
鹿屿二向箔18 小时前
基于SSM(Spring + Spring MVC + MyBatis)框架的咖啡馆管理系统
spring·mvc·mybatis
aloha_7891 天前
从零记录搭建一个干净的mybatis环境
java·笔记·spring·spring cloud·maven·mybatis·springboot
毕业设计制作和分享1 天前
ssm《数据库系统原理》课程平台的设计与实现+vue
前端·数据库·vue.js·oracle·mybatis
paopaokaka_luck1 天前
基于Spring Boot+Vue的助农销售平台(协同过滤算法、限流算法、支付宝沙盒支付、实时聊天、图形化分析)
java·spring boot·小程序·毕业设计·mybatis·1024程序员节
cooldream20091 天前
Spring Boot中集成MyBatis操作数据库详细教程
java·数据库·spring boot·mybatis
不像程序员的程序媛1 天前
mybatisgenerator生成mapper时报错
maven·mybatis
小布布的不1 天前
MyBatis 返回 Map 或 List<Map>时,时间类型数据,默认为LocalDateTime,响应给前端默认含有‘T‘字符
前端·mybatis·springboot
背水2 天前
Mybatis基于注解的关系查询
mybatis