龙空技术网

3 fluent-mybatis springboot整合设置 及 控制台完整SQL打印

EYE33 119

前言:

当前你们对“spring 数据源配置打印sql”可能比较看重,同学们都想要分析一些“spring 数据源配置打印sql”的相关文章。那么小编也在网络上搜集了一些对于“spring 数据源配置打印sql””的相关内容,希望朋友们能喜欢,咱们快快来学习一下吧!

关键bean(MapperFactory)设置

在执行pom中相应构件引入了 但是在执行SQL时却报错了

请注意提示

设置好对应的MapperFactory的Bean即可

package com.project.global.config;import cn.org.atool.fluent.mybatis.spring.MapperFactory;import com.project.global.interceptor.MybatisInterceptor;import org.mybatis.spring.boot.autoconfigure.ConfigurationCustomizer;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;/** * @author LWB * @description */@Configurationpublic class MybatisConfig {    // 这是mybatis的拦截器 用于控制完整的SQL输出 详见下文    @Bean    ConfigurationCustomizer mybatisConfigurationCustomizer() {        return configuration -> configuration.addInterceptor(new MybatisInterceptor());    }    // 这是根据提示 设置的MapperFactory    @Bean    public MapperFactory mapperFactory() {        return new MapperFactory();    }}

利用mybatis的拦截器 实现完整SQL打印

package com.project.global.interceptor;import cn.hutool.core.text.StrFormatter;import com.project.global.SpringContextUtil;import com.project.global.config.ProjectConifg;import com.project.mybatis.sys.entity.SysMsg;import com.project.service.sys.MsgService;import com.project.support.constant.SysConst;import lombok.extern.slf4j.Slf4j;import org.apache.ibatis.cache.CacheKey;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.mapping.ParameterMode;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.text.SimpleDateFormat;import java.util.Date;import java.util.List;import java.util.Properties;import java.util.regex.Matcher;/** * mybaits拦截器:用于输出完整的SQL * @author LWB * */@Intercepts({        @Signature(method = "update", type = Executor.class, args = { MappedStatement.class, Object.class } ),        @Signature(method = "query",  type = Executor.class, args = { MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class }),        @Signature(method = "query",  type = Executor.class, args = { MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class, CacheKey.class, BoundSql.class})})@Slf4jpublic class MybatisInterceptor implements Interceptor {    private static final DateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");    @Override    public Object intercept(Invocation invocation) throws Throwable {        MappedStatement mappedStatement = (MappedStatement) invocation.getArgs()[0];        Object parameterObject = null;        if (invocation.getArgs().length > 1) {            parameterObject = invocation.getArgs()[1];        }        long start = System.currentTimeMillis();        String statementId = mappedStatement.getId();        BoundSql boundSql = mappedStatement.getBoundSql(parameterObject);        Configuration configuration = mappedStatement.getConfiguration();        String sql = getSql(boundSql, parameterObject, configuration);        Object result = null;        try{            result = invocation.proceed();        }catch (Exception e){            //执行异常时,也打印SQL,以便排查            String sqlInfo = StrFormatter.format("\nid:{},\n异常SQL信息:{}", statementId, sql);            e.printStackTrace();            log.error(sqlInfo);        }        long end = System.currentTimeMillis();        long timing = end - start;        String sqlInfo = StrFormatter.format("\nid:{},执行sql耗时:{} ms\n完整SQL信息:{}", statementId, timing, sql);        // 输出sql       log.info(sqlInfo);                return result;    }    @Override    public Object plugin(Object target) {        if (target instanceof Executor) {            return Plugin.wrap(target, this);        }        return target;    }    @Override    public void setProperties(Properties properties) {    }    private String getSql(BoundSql boundSql, Object parameterObject, Configuration configuration) {        String sql = boundSql.getSql().replaceAll("[\\s]+", " ");        List<ParameterMapping> parameterMappings = boundSql.getParameterMappings();        TypeHandlerRegistry typeHandlerRegistry = configuration.getTypeHandlerRegistry();        if (parameterMappings != null) {            for (int i = 0; i < parameterMappings.size(); i++) {                ParameterMapping parameterMapping = parameterMappings.get(i);                if (parameterMapping.getMode() != ParameterMode.OUT) {                    Object value;                    String propertyName = parameterMapping.getProperty();                    if (boundSql.hasAdditionalParameter(propertyName)) {                        value = boundSql.getAdditionalParameter(propertyName);                    } else if (parameterObject == null) {                        value = null;                    } else if (typeHandlerRegistry.hasTypeHandler(parameterObject.getClass())) {                        value = parameterObject;                    } else {                        MetaObject metaObject = configuration.newMetaObject(parameterObject);                        value = metaObject.getValue(propertyName);                    }                    sql = replacePlaceholder(sql, value);                }            }        }        return sql;    }    private String replacePlaceholder(String sql, Object propertyValue) {        String result;        if (propertyValue != null) {            if (propertyValue instanceof String) {                result = "'" + propertyValue + "'";            } else if (propertyValue instanceof Date) {                result = "'" + DATE_FORMAT.format(propertyValue) + "'";            } else {                result = propertyValue.toString();            }        } else {            result = "null";        }        return sql.replaceFirst("\\?", Matcher.quoteReplacement(result));    }    }

标签: #spring 数据源配置打印sql