package com.glxp.api.handler; import org.apache.ibatis.plugin.*; import org.apache.ibatis.reflection.MetaObject; import org.apache.ibatis.reflection.SystemMetaObject; import org.apache.ibatis.executor.statement.StatementHandler; import java.sql.Connection; import java.sql.SQLException; import java.util.Properties; import javax.sql.DataSource; @Intercepts({ @Signature(type = StatementHandler.class, method = "prepare", args = {Connection.class, Integer.class}) }) public class MybatisDmHandler implements Interceptor { @Override public Object intercept(Invocation invocation) throws Throwable { // 获取被拦截的 StatementHandler 对象 StatementHandler statementHandler = (StatementHandler) invocation.getTarget(); MetaObject metaObject = SystemMetaObject.forObject(statementHandler); // 获取 SQL 语句 String sql = (String) metaObject.getValue("delegate.boundSql.sql"); System.out.println("拦截到的 SQL: " + sql); String processedSql = camelToSnake(sql); // // 可在此对 SQL 进行处理,例如修改 SQL、添加日志等 // String processedSql = sql.toUpperCase(); System.out.println("处理后的 SQL: " + processedSql); metaObject.setValue("delegate.boundSql.sql", processedSql); // 继续执行原方法 return invocation.proceed(); } @Override public Object plugin(Object target) { // 将目标对象包装成代理对象 return Plugin.wrap(target, this); } @Override public void setProperties(Properties properties) { // 可在此设置拦截器的属性 } public String camelToSnake(String camelCase) { // 使用正则表达式替换大写字母为下划线加小写字母 return camelCase.replaceAll("(?<=[a-z])([A-Z])", "_$1").toLowerCase(); } }