千家信息网

mybatis如何使用拦截器interceptor对sql打印,使执行的sql在日志中可见

发表于:2024-09-25 作者:千家信息网编辑
千家信息网最后更新 2024年09月25日,这篇文章主要介绍"mybatis如何使用拦截器interceptor对sql打印,使执行的sql在日志中可见",在日常操作中,相信很多人在mybatis如何使用拦截器interceptor对sql打印
千家信息网最后更新 2024年09月25日mybatis如何使用拦截器interceptor对sql打印,使执行的sql在日志中可见

这篇文章主要介绍"mybatis如何使用拦截器interceptor对sql打印,使执行的sql在日志中可见",在日常操作中,相信很多人在mybatis如何使用拦截器interceptor对sql打印,使执行的sql在日志中可见问题上存在疑惑,小编查阅了各式资料,整理出简单好用的操作方法,希望对大家解答"mybatis如何使用拦截器interceptor对sql打印,使执行的sql在日志中可见"的疑惑有所帮助!接下来,请跟着小编一起来学习吧!

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.plugin.Interceptor;import org.apache.ibatis.plugin.Intercepts;import org.apache.ibatis.plugin.Invocation;import org.apache.ibatis.plugin.Plugin;import org.apache.ibatis.plugin.Signature;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.Date;import java.util.List;import java.util.Locale;import java.util.Properties;/** * @author kxd * @date 2019/10/25 15:55 * description: */@Intercepts({        @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 LogInterceptor implements Interceptor {    /**     * 是否显示语句的执行时间     */    public static final String PROPERTIES_KEY_ENABLE_EXECUTOR_TIME = "enableExecutorTIme";    public static final String NO = "NO";    public static final String YES = "YES";    private String enableExecutorTime;    /**     * 执行逻辑     *     * @param invocation     * @return     * @throws Throwable     */    @Override    public Object intercept(Invocation invocation) throws Throwable {        if (enableExecutorTime.equals(YES)) {            MappedStatement mappedStatement = (MappedStatement) invocation.getArgs()[0];            //这里是为了找到上层是哪个方法触发了这个拦截器            Object parameter = null;            if (invocation.getArgs().length > 1) {                parameter = invocation.getArgs()[1];            }            String sqlId = mappedStatement.getId();            BoundSql boundSql = mappedStatement.getBoundSql(parameter);            Configuration configuration = mappedStatement.getConfiguration();            long sqlStartTime = System.currentTimeMillis();            Object next = invocation.proceed();            long sqlEndTime = System.currentTimeMillis();            String sql = getSql(configuration, boundSql, sqlId);            String sqlTimeLog = sqlId.concat(">>runs :").concat(String.valueOf(sqlEndTime - sqlStartTime)).concat("ms");            log.info(">>>>>>>>>>>>>runs method:{}", sqlTimeLog);            log.info(">>>>>>>>>>>>>content:{}", sql);            return next;        }        return invocation.proceed();    }    private String getSql(Configuration configuration, BoundSql boundSql, String sqlId) {        return sqlId + ">>execute sql:" + assembleSql(configuration, boundSql);    }    /**     * 组装sql信息     *     * @param configuration     * @param boundSql     * @return     */    private String assembleSql(Configuration configuration, BoundSql boundSql) {        Object sqlParameter = boundSql.getParameterObject();        List parameterMappings = boundSql.getParameterMappings();        String sql = boundSql.getSql().replaceAll("[\\s+]", "").replaceAll("from", "\n\tFROM\n\t").replaceAll("select", "\n\tSELECT\t\n");        if (parameterMappings.size() > 0 && sqlParameter != null) {            TypeHandlerRegistry typeHandlerRegistry = configuration.getTypeHandlerRegistry();            if (typeHandlerRegistry.hasTypeHandler(sqlParameter.getClass())) {                sql = sql.replaceFirst("\\?", getParameterValue(sqlParameter));            } else {                MetaObject metaObject = configuration.newMetaObject(sqlParameter);                for (ParameterMapping parameterMapping : parameterMappings) {                    String propertyName = parameterMapping.getProperty();                    if (metaObject.hasGetter(propertyName)) {                        Object obj = metaObject.getValue(propertyName);                        sql = sql.replaceFirst("\\?", getParameterValue(obj));                    } else if (boundSql.hasAdditionalParameter(propertyName)) {                        Object obj = boundSql.getAdditionalParameter(propertyName);                        sql = sql.replaceFirst("\\?", getParameterValue(obj));                    }                }            }        }        return sql;    }    /**     * 获取参数对应string值     *     * @param obj     * @return     */    private String getParameterValue(Object obj) {        String value = "";        if (obj instanceof String) {            value = "'".concat(obj.toString()).concat("'");        } else if (obj instanceof Date) {            DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.DEFAULT, DateFormat.DEFAULT, Locale.CHINA);            value = "'".concat(dateFormat.format(new Date())) + "'";        } else {            if (obj != null) {                value = obj.toString();            } else {                value = "";            }        }        return value != null ? makeStringAllRegExp(value) : value;    }    /**     * 转义正则特殊字符串     *     * @param str     * @return     */    private String makeStringAllRegExp(String str) {        if (str != null && !str.equals("")) {            return str.replace("\\", "\\\\").replace("*", "\\*")                    .replace("+", "\\+").replace("|", "\\|")                    .replace("{", "\\{").replace("}", "\\}")                    .replace("(", "\\(").replace(")", "\\)")                    .replace("^", "\\^").replace("$", "\\$")                    .replace("[", "\\[").replace("]", "\\]")                    .replace("?", "\\?").replace(",", "\\,")                    .replace(".", "\\.").replace("&", "\\&");        }        return str;    }    /**     * 返回代理对象     *     * @param target     * @return     */    @Override    public Object plugin(Object target) {        return Plugin.wrap(target, this);    }    /**     * 设置属性信息     *     * @param properties     */    @Override    public void setProperties(Properties properties) {        if (properties != null) {            String executorTimeValue = properties.getProperty(PROPERTIES_KEY_ENABLE_EXECUTOR_TIME);            if (executorTimeValue != null) {                enableExecutorTime = executorTimeValue;            }        }    }}

到此,关于"mybatis如何使用拦截器interceptor对sql打印,使执行的sql在日志中可见"的学习就结束了,希望能够解决大家的疑惑。理论与实践的搭配能更好的帮助大家学习,快去试试吧!若想继续学习更多相关知识,请继续关注网站,小编会继续努力为大家带来更多实用的文章!

拦截器 日志 学习 信息 方法 更多 帮助 实用 特殊 接下来 上层 参数 字符 字符串 对象 属性 文章 时间 正则 理论 数据库的安全要保护哪些东西 数据库安全各自的含义是什么 生产安全数据库录入 数据库的安全性及管理 数据库安全策略包含哪些 海淀数据库安全审计系统 建立农村房屋安全信息数据库 易用的数据库客户端支持安全管理 连接数据库失败ssl安全错误 数据库的锁怎样保障安全 深圳java软件开发教程 上海网络安全检测中心副主任 高密天气预报软件开发 应用软件开发在香港 数据库实时更新的代码 安仁计算机软件开发培训机构 excel提高软件开发效率 方舟服务器与主机失去连接 网络安全灯图片大全 陕西会议无纸化软件开发 qq与服务器连接中断是为什么 山东电力集团 软件开发 陕西服务器回收厂家云空间 网络安全三六零 率土之滨多久出一个服务器 软件开发工具发展方向 创建名为YGGL的数据库 数据安全是否包括网络安全 北京智运时空网络技术有限公司 什么叫服务器安全加固系统 北京国健慧康网络技术 不同数据库之间的link 信息系统与数据库技术电子书 用什么软件开发平台 数据库基础应用配套练习 软件开发流程aspice 阿里云服务器ftp如何设置 墨攻网络安全平台 服务器文件提示无管理员权限 长沙手机软件开发怎样收费
0