需求分析

在调试springboot项目中,有些方法操作了很多数据库表,在调试项目时我想快速知道操作了哪些数据库表。于是我使用自定义拦截器的方式实现这个需求;注意:这个拦截器假设SQL语句的格式是标准的,并且表名称可以直接从FROM或UPDATE关键字后面提取。对于更复杂的SQL语句,可能需要更复杂的逻辑来正确提取表名称

首先,创建自定义拦截器

import org.apache.ibatis.executor.statement.StatementHandler;
import org.apache.ibatis.mapping.BoundSql;
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.session.ResultHandler;

import java.sql.Statement;
import java.util.Properties;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Intercepts({
    @Signature(type = StatementHandler.class, method = "query", args = {Statement.class, ResultHandler.class}),
    @Signature(type = StatementHandler.class, method = "update", args = {Statement.class}),
    @Signature(type = StatementHandler.class, method = "batch", args = {Statement.class})
})
public class TableNameInterceptor implements Interceptor {
	
	//定义正则表达式,提取出sql语句中的关键字
    private static final Pattern TABLE_NAME_PATTERN = Pattern.compile("(FROM|UPDATE)\\s+([\\w\\._]+)");

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        StatementHandler statementHandler = (StatementHandler) invocation.getTarget();
        BoundSql boundSql = statementHandler.getBoundSql();
        String sql = boundSql.getSql();

        // 解析SQL语句,提取表名称
        Matcher matcher = TABLE_NAME_PATTERN.matcher(sql);
        while (matcher.find()) {
            String tableName = matcher.group(2);
            System.out.println("操作了数据库表,名称为: " + tableName);
        }

        return invocation.proceed();
    }

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

    @Override
    public void setProperties(Properties properties) {
        // 这里可以用来配置拦截器的属性
    }
}

注册拦截器

import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class MyBatisConfig {

    @Bean
    public TableNameInterceptor tableNameInterceptor() {
        return new TableNameInterceptor();
    }

    // 根据你的配置,可能需要另外的方式来注册拦截器
}

最后,在配置文件中开启mybatis-plus的sql日志打印,并且确保你的Spring Boot应用能够扫描到MyBatisConfig类,这一步不多赘述

Logo

DAMO开发者矩阵,由阿里巴巴达摩院和中国互联网协会联合发起,致力于探讨最前沿的技术趋势与应用成果,搭建高质量的交流与分享平台,推动技术创新与产业应用链接,围绕“人工智能与新型计算”构建开放共享的开发者生态。

更多推荐