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;
    }
}
相关推荐
bing_15813 小时前
跨多个微服务使用 Redis 共享数据时,如何管理数据一致性?
redis·微服务·mybatis
云之兕16 小时前
MyBatis 的动态 SQL
数据库·sql·mybatis
loser.loser1 天前
QQ邮箱发送验证码(Springboot)
java·spring boot·mybatis
毅航1 天前
Trae复刻Mybatis之旅(一):创建SqlSession会话,构建代理
后端·mybatis·trae
潮流coder1 天前
mybatis的if判断==‘1‘不生效,改成‘1‘.toString()才生效的原因
java·tomcat·mybatis
BillKu1 天前
Java + Spring Boot + Mybatis 实现批量插入
java·spring boot·mybatis
dog shit1 天前
web第十次课后作业--Mybatis的增删改查
android·前端·mybatis
emo了小猫1 天前
Mybatis #{} 和 ${}区别,使用场景,LIKE模糊查询避免SQL注入
数据库·sql·mysql·mybatis
yuren_xia2 天前
Spring Boot + MyBatis 集成支付宝支付流程
spring boot·tomcat·mybatis
神仙别闹2 天前
基于Java(SpringBoot、Mybatis、SpringMvc)+MySQL实现(Web)小二结账系统
java·spring boot·mybatis