通过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

相关推荐
计算机毕设定制辅导-无忧学长4 小时前
西门子 PLC 与 Modbus 集成:S7-1500 RTU/TCP 配置指南(一)
服务器·数据库·tcp/ip
程序员柳5 小时前
基于微信小程序的校园二手交易平台、微信小程序校园二手商城源代码+数据库+使用说明,layui+微信小程序+Spring Boot
数据库·微信小程序·layui
梦在深巷、5 小时前
MySQL/MariaDB数据库主从复制之基于二进制日志的方式
linux·数据库·mysql·mariadb
IT乌鸦坐飞机5 小时前
ansible部署数据库服务随机启动并创建用户和设置用户有完全权限
数据库·ansible·centos7
IT_10245 小时前
Spring Boot项目开发实战销售管理系统——数据库设计!
java·开发语言·数据库·spring boot·后端·oracle
耀耀_很无聊6 小时前
07_通过 Mybatis 自动填充记录的创建时间和更新时间
mybatis
祁思妙想7 小时前
八股学习(三)---MySQL
数据库·学习·mysql
惊骇世俗王某人7 小时前
1.MySQL之如何定位慢查询
数据库·mysql
程序员张37 小时前
SQL分析与打印-p6spy组件
spring boot·sql·mybatis·mybatisplus·p6spy
秦歌6668 小时前
向量数据库-Milvus快速入门
数据库·milvus