基于Mybatis Interceptor获取SQL

核心代码如下:

<br />import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.MappedStatement;
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 org.apache.ibatis.session.RowBounds;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Properties;
import com.google.common.base.Strings;

@Intercepts({
        @Signature(type = Executor.class, method = "query", args = {MappedStatement.class, Object.class,
                RowBounds.class, ResultHandler.class}),
        @Signature(type = Executor.class, method = "update", args = {MappedStatement.class, Object.class})})
public class CommonMyBatisInterceptor implements Interceptor {
    @Override
        public Object intercept(Invocation invocation) throws Throwable {
            Object[] args = invocation.getArgs();
            MappedStatement mappedStatement = (MappedStatement) args[0];
            // 得到 类名-方法
            String[] strArr = mappedStatement.getId().split("\\.");
            String traceKey = strArr[strArr.length - 2] + "." + strArr[strArr.length - 1];

            String sqlType = mappedStatement.getSqlCommandType().name();
            //sqlId
            String sqlId = mappedStatement.getId();

            String sqlText = "";
            String sqlParameterStr = "";
            if (args.length > 1) {
                sqlText = mappedStatement.getBoundSql(args[1]).getSql();
                sqlParameterStr = mappedStatement.getBoundSql(args[1]).getParameterObject().toString();
            }

            return metrics(invocation, traceKey, sqlType, sqlId, sqlText, sqlParameterStr);
        }
}
本文版权归作者所有,禁止一切形式的转载,复制等操作
赞赏

微信赞赏支付宝赞赏

发表评论

电子邮件地址不会被公开。 必填项已用*标注