通过mybatis的拦截器对SQL进行打标

1、背景

在我们开发的过程中,一般需要编写各种SQL语句,万一生产环境出现了慢查询,那么我们如何快速定位到底是程序中的那个SQL出现的问题呢?

2、解决方案

如果我们的数据访问层使用的是mybatis的话,那么我们可以通过mybatis提供的拦截器拦截系统中的SQL,然后将 mapper的命名空间和id追加到原始SQL的末尾,当作一个注释,这样不就可以实现吗? 类似效果如下:

sql 复制代码
select * from customer where phone = 'aaaaa';/**com.huan.study.mybatis.mappers.CustomerMapper.findCustomer*/

3、核心实现步骤

1、拦截器拦截SQL进行打标

java 复制代码
package com.huan.study.mybatis.plugin;

import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.executor.statement.StatementHandler;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.plugin.*;
import org.apache.ibatis.reflection.MetaObject;
import org.apache.ibatis.reflection.SystemMetaObject;

import java.sql.Connection;

/**
 * 在原始的Sql语句后面追加 sql id,方面知道当前查询语句是那个mapper文件中的
 *
 * @author huan
 * @date 2025/3/11 - 00:30
 */
@Slf4j
@Intercepts(
        {
                @Signature(type = StatementHandler.class, method = "prepare", args = {Connection.class, Integer.class})
        }
)
public class PrintSqlIdInterceptor implements Interceptor {
    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        StatementHandler statementHandler = (StatementHandler) invocation.getTarget();
        MetaObject metaStatementHandler = MetaObject.forObject(statementHandler,
                SystemMetaObject.DEFAULT_OBJECT_FACTORY,
                SystemMetaObject.DEFAULT_OBJECT_WRAPPER_FACTORY,
                SystemMetaObject.NULL_META_OBJECT.getReflectorFactory());
        BoundSql boundSql = statementHandler.getBoundSql();
        MappedStatement mappedStatement = (MappedStatement) metaStatementHandler.getValue("delegate.mappedStatement");
        String id = mappedStatement.getId();
        log.info("sql语句的id : {}", id);

        String sql = boundSql.getSql();
        if (!sql.endsWith(";")) {
            sql += ";";
        }
        sql = sql + "/**" + id + "*/";

        metaStatementHandler.setValue("delegate.boundSql.sql", sql);
        return invocation.proceed();
    }

    @Override
    public Object plugin(Object target) {
        return Plugin.wrap(target, this);
    }
}

2、配置插件

mybatis-config.xml中进行插件的配置

xml 复制代码
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <plugins>
        <plugin interceptor="com.huan.study.mybatis.plugin.PrintSqlIdInterceptor"/>
    </plugins>

</configuration>

4、实现效果如下

sql 复制代码
select * from customer where phone = 'aaaaa';/**com.huan.study.mybatis.mappers.CustomerMapper.findCustomer*/
insert into customer(phone,address) values ('12345','湖北');/**com.huan.study.mybatis.mappers.CustomerMapper.addCustomer*/

可以看到我们对每个SQL都进行了打标,方便SQL的追踪

5、完整代码

https://gitee.com/huan1993/spring-cloud-parent/tree/master/mybatis/mybatis-sql-marking

相关推荐
洛北辰南1 小时前
系统架构设计师—案例分析—数据库篇—分布式缓存技术
数据库·分布式·系统架构·缓存技术
winner88812 小时前
Hive SQL 精进系列:PERCENTILE_APPROX 搞定分位数
hive·hadoop·sql
星光璀璨山河无恙2 小时前
【MySQL】数据库简要介绍和简单应用
数据库·mysql
px52133442 小时前
Solder leakage problems and improvement strategies in electronics manufacturing
java·前端·数据库·pcb工艺
啥都想学的又啥都不会的研究生3 小时前
Redis设计与实现-数据持久化
java·数据库·redis·笔记·缓存·面试
新知图书3 小时前
Windows下安装MongoDB 8
数据库·windows·mongodb
fly spider3 小时前
Mybatis语法bug
bug·mybatis
jay丿3 小时前
Django 分页操作详解
数据库·django·sqlite
誰能久伴不乏3 小时前
深入理解 Qt 系统托盘图标:创建自定义的系统托盘图标类
数据库·qt·microsoft
cherry52303 小时前
【第4章】项目实战-亿级电商系统需求分析
大数据·数据库·架构·需求分析