Created
December 12, 2019 02:59
-
-
Save wreulicke/ec56feedc1c368024cd892699b4d8c38 to your computer and use it in GitHub Desktop.
Add SQL Comment with RequestID to all sql.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.wreulicke.github.mybatis; | |
import org.apache.ibatis.executor.statement.StatementHandler; | |
import org.apache.ibatis.mapping.BoundSql; | |
import org.apache.ibatis.mapping.MappedStatement; | |
import org.apache.ibatis.mapping.SqlCommandType; | |
import org.apache.ibatis.plugin.Interceptor; | |
import org.apache.ibatis.plugin.Invocation; | |
import org.slf4j.MDC; | |
import org.springframework.jdbc.core.SqlProvider; | |
import org.springframework.stereotype.Component; | |
import org.springframework.util.ReflectionUtils; | |
import java.lang.reflect.Field; | |
import java.lang.reflect.Type; | |
import java.util.Properties; | |
@Component | |
public class RequestIdInterceptor implements Interceptor { | |
@Override | |
public Object intercept(Invocation invocation) throws Throwable { | |
return null; | |
} | |
@Override | |
public Object plugin(Object target) { | |
String requestid = MDC.get("requestid"); | |
if (requestid == null) { | |
return target; | |
} | |
try { | |
Type[] types = target.getClass().getGenericInterfaces(); | |
for(Type type : types) { | |
if(type == StatementHandler.class) { | |
StatementHandler sh = (StatementHandler) target; | |
Field field = ReflectionUtils.findField(sh.getClass(), "delegate"); | |
ReflectionUtils.makeAccessible(field); | |
Object delegate = ReflectionUtils.getField(field, target); | |
Field boundSqlField = ReflectionUtils.findField(delegate.getClass(), "boundSql"); | |
ReflectionUtils.makeAccessible(boundSqlField); | |
BoundSql boundSql = (BoundSql) ReflectionUtils.getField(boundSqlField, delegate); | |
String sql = boundSql.getSql(); | |
Field sqlField = ReflectionUtils.findField(boundSql.getClass(), "sql"); | |
ReflectionUtils.makeAccessible(sqlField); | |
String newSql = sql + " /* RequestID:" + requestid + "*/"; | |
ReflectionUtils.setField(sqlField, boundSql, newSql); | |
} | |
} | |
return target; | |
} catch(Exception e) { | |
throw new AssertionError(e.getMessage(), e); | |
} | |
} | |
@Override | |
public void setProperties(Properties properties) { | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment