Springboot + Mybatis 实现sql打印

参照这个视频:https://www.bilibili.com/video/BV1MS411N7mn/?vd_source=90ebeef3261cec486646b6583e9f45f5

实现mybatis对外暴露的接口Interceptor

使用@Intercepts接口,这里的写法参照mybatis-plus中的拦截器写法

java 复制代码
@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}),
        @Signature(type = Executor.class, method = "query", args = {MappedStatement.class, Object.class, RowBounds.class
                , ResultHandler.class, CacheKey.class, BoundSql.class}),
})
public class MybatisSqlPrint implements Interceptor {

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        // 计算这一次SQL执行钱后的时间,统计一下执行耗时
        long startTime = System.currentTimeMillis();
        Object proceed = invocation.proceed();
        long endTime = System.currentTimeMillis();

        String printSql = null;
        try {
            // 通过generateSql方法拿到最终生成的SQL
            printSql = generateSql(invocation);
        }catch (Exception exception){
            System.err.println(String.format("获取sql异常:%s",exception));
        }finally {
            // 拼接日志打印过程
            long costTime = endTime - startTime;
            System.out.println(String.format("\n 执行SQL耗时:%dms \n 执行SQL:%s",costTime,printSql));
        }
        return proceed;
    }

    private static String generateSql(Invocation invocation){
        // 获取到BoundSql以及Configuration对象
        // BoundSql 对象存储了一条具体的 SQL 语句及其相关参数信息。
        // Configuration 对象保存了 MyBatis 框架运行时所有的配置信息
        MappedStatement statement = (MappedStatement) invocation.getArgs()[0];
        Object parameter = null;
        if (invocation.getArgs().length>1){
            parameter = invocation.getArgs()[1];
        }
        Configuration configuration = statement.getConfiguration();
        BoundSql boundSql = statement.getBoundSql(parameter);

        // 获取参数对象
        Object parameterObject = boundSql.getParameterObject();
        // 获取参数映射
        List<ParameterMapping> params = boundSql.getParameterMappings();
        // 获取到执行的SQL
        String sql = boundSql.getSql();
        // SQL中多个空格使用一个空格代替
        sql = sql.replaceAll("[\\s]+", " ");
        if (!ObjectUtils.isEmpty(params) && !ObjectUtils.isEmpty(parameterObject)){
            // TypeHandlerRegistry 是 MyBatis 用来管理 TypeHandler 的注册器。TypeHandler 用于在 Java 类型和 JDBC 类型之间进行转换
            TypeHandlerRegistry typeHandlerRegistry = configuration.getTypeHandlerRegistry();
            // 如果参数对象的类型有对应的 TypeHandler,则使用 TypeHandler 进行处理
            if (typeHandlerRegistry.hasTypeHandler(parameterObject.getClass())){
                sql = sql.replaceFirst("\\?", Matcher.quoteReplacement(getParameterValue(parameterObject)));
            }else {
                // 否则,逐个处理参数映射
                for (ParameterMapping param : params) {
                    // 获取参数的属性名
                    String propertyName = param.getProperty();
                    MetaObject metaObject = configuration.newMetaObject(parameterObject);
                    // 检查对象中是否存在该属性的 getter 方法,如果存在就取出来进行替换
                    if (metaObject.hasGetter(propertyName)){
                        Object obj = metaObject.getValue(propertyName);
                        sql = sql.replaceFirst("\\?", Matcher.quoteReplacement(getParameterValue(obj)));
                        // 检查 BoundSql 对象中是否存在附加参数。附加参数可能是在动态 SQL 处理中生成的,有的话就进行替换
                    }else if (boundSql.hasAdditionalParameter(propertyName)){
                        Object obj = boundSql.getAdditionalParameter(propertyName);
                        sql = sql.replaceFirst("\\?", Matcher.quoteReplacement(getParameterValue(obj)));
                    }else {
                        // 如果都没有,说明SQL匹配不上,带上"缺失"方便找问题
                        sql = sql.replaceFirst("\\?", "缺失");
                    }
                }
            }
        }
        return sql;
    }

    private static String getParameterValue(Object object) {
        String value = "";
        if (object instanceof String){
            value = "'" + object.toString() + "'";
        }else if (object instanceof Date){
            DateFormat format = DateFormat.getDateTimeInstance(DateFormat.DEFAULT, DateFormat.DEFAULT, Locale.CHINA);
            value = "'" + format.format((Date) object) + "'";
        } else if (!ObjectUtils.isEmpty(object)) {
            value = object.toString();
        }
        return value;
    }

}

最后将拦截器添加到mybatis中

java 复制代码
@Configuration
public class MybatisConfig {
    public MybatisConfig() {
        System.out.println("MybatisConfig loaded");
    }
    SqlSessionFactory sqlSessionFactory;

    @Autowired
    public void setSqlSessionFactory(SqlSessionFactory sqlSessionFactory) {
        this.sqlSessionFactory = sqlSessionFactory;
    }

    @PostConstruct
    public void addInterceptor(){
        sqlSessionFactory.getConfiguration().addInterceptor(new MybatisSqlPrint());
    }

}

实现效果

相关推荐
杨DaB44 分钟前
【SpringBoot】Dubbo、Zookeeper
spring boot·后端·zookeeper·dubbo·java-zookeeper
柯南二号1 小时前
【后端】SpringBoot中HttpServletRequest参数为啥不需要前端透传
前端·spring boot·后端
盖世英雄酱581362 小时前
第一个RAG项目遇到的问题
java·spring boot
Java水解2 小时前
深入理解 SQL 中的 COALESCE、NULLIF 和 IFNULL 函数
后端·sql
秋千码途4 小时前
一道同分排名的SQL题
数据库·sql
RainbowSea5 小时前
伙伴匹配系统(移动端 H5 网站(APP 风格)基于Spring Boot 后端 + Vue3 - 06
java·spring boot·后端
RainbowSea5 小时前
伙伴匹配系统(移动端 H5 网站(APP 风格)基于Spring Boot 后端 + Vue3 - 05
vue.js·spring boot·后端
秋难降6 小时前
零基础学SQL(八)——事务
数据库·sql·mysql
华仔啊6 小时前
3行注解干掉30行日志代码!Spring AOP实战全程复盘
java·spring boot·后端
Mi_Manchikkk8 小时前
Java高级面试实战:Spring Boot微服务与Redis缓存整合案例解析
java·spring boot·redis·缓存·微服务·面试