1. 程式人生 > >Mybatis檢視完整SQL及執行效能

Mybatis檢視完整SQL及執行效能

能不能直接把?引數拼接完了以後SQL給我?

在開發的過程中,資料不對的時候,我們會去日誌中找到 具體的sql 執行語句
但是往往是這樣的

2017-08-30-14-35-23 [DEBUG] [main] [selectRecommendGoodsForStoreApp_132] - ==>  Preparing: SELECT sk.SKU_ID AS skuId, sk.SKU_IMG_PATH AS skuImgPath, sk.SKU_NAME AS skuName, sk.SKU_NORMS AS skuNorms, sk.QUALITY_PERIOD AS qualityPeriod, sk.SKU_PACKAGE_NUM_1 as
skuPackageNum1, sk.SKU_PACKAGE_NUM_2 as skuPackageNum2, sk.SKU_PACKAGE_NUM_3 as skuPackageNum3, sk.SKU_PACKAGE_UNIT_1 as skuPackageUnit1, sk.SKU_PACKAGE_UNIT_2 as skuPackageUnit2, sk.SKU_PACKAGE_UNIT_3 as skuPackageUnit3, sh.SELL_PRICE AS sellPrice, sh.USER_ID as supplierId, sh.SHELF_ID as shelfId, sh.WAREHOUSE_ID as
warehouseId, sh.PROMOTION_PRICE as promotionPrice FROM ess_sku_recommend AS re LEFT JOIN ess_sku_custom as sk ON sk.SKU_ID=re.SKU_ID LEFT JOIN ess_shelf_info as sh ON sh.SKU_ID = sk.SKU_ID WHERE 1=1 and sh.WAREHOUSE_ID in ( ? , ? , ? , ? , ? , ? , ? , ? , ? , ? , ? , ? , ? ) group by sk.sku_id
2017
-08-30-14-35-23 [DEBUG] [main] [selectRecommendGoodsForStoreApp_132] - ==> Parameters: 147(String), a07bfd2e052b4513b308e969e4cc6eea(String), W10000001(String), W10000002(String), W10000003(String), W10000006(String), W10000007(String), W11708261601220001(String), W11708281000390002(String), W11708281001220003(String), W11708281001540004(String), W11708281506390001(String), Wsdfsdf(String)

這裡寫圖片描述


看到那一堆?????? 了嗎?
上面的 程式碼 是 帶有? 的 預執行 sql 語句,現在好了,你看看第二個程式碼塊裡的 具體引數吧,你 不覺得 一個一個 的 去 替換然後 查詢,然後看結果。。。。。 這個過程很反人類嗎?


你只需要這段程式碼

下面這個是一個 mybatis plugin,放到你的 專案當中,然後在 mybatis 的配置檔案中 加上 這個 plugin。
至於如何加plugin ,這個根據 mybatis 版本不同,以及 具體的配置規則不一樣
請大家自行適配吧。

這個功能加上去之後
1.可以打印出最後執行的SQL(?已經給你替換成具體的引數了)
2.記錄這個SQL執行的時間。這一點對於效能調優 還是很有幫助了

import java.text.DateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.Properties;

import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.ParameterMapping;
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.reflection.MetaObject;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;
import org.apache.ibatis.type.TypeHandlerRegistry;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@Intercepts({ @Signature(type = Executor.class, method = "update", args = { MappedStatement.class, Object.class }),
        @Signature(type = Executor.class, method = "query", args = { MappedStatement.class, Object.class,
                RowBounds.class, ResultHandler.class }) })
public class SqlTimeInterceptor implements Interceptor {

    @SuppressWarnings("unused")
    private Properties properties;
    private static Logger log = LoggerFactory.getLogger(SqlTimeInterceptor.class);

    public Object intercept(Invocation invocation) throws Throwable {
        MappedStatement mappedStatement = (MappedStatement) invocation.getArgs()[0];
        Object parameter = null;
        if (invocation.getArgs().length > 1) {
            parameter = invocation.getArgs()[1];
        }
        String sqlId = mappedStatement.getId();
        BoundSql boundSql = mappedStatement.getBoundSql(parameter);
        Configuration configuration = mappedStatement.getConfiguration();
        Object returnValue = null;
        long start = System.currentTimeMillis();
        returnValue = invocation.proceed();
        long end = System.currentTimeMillis();
        long time = (end - start);
        if (time > 1) {
            String sql = getSql(configuration, boundSql, sqlId, time);
            log.info(sql);
        }
        return returnValue;
    }

    public static String getSql(Configuration configuration, BoundSql boundSql, String sqlId, long time) {
        String sql = showSql(configuration, boundSql);
        StringBuilder str = new StringBuilder(100);
        str.append(sqlId);
        str.append(":");
        str.append(sql);
        str.append(": 執行耗時");
        str.append(time);
        str.append("ms");
        return str.toString();
    }

    private static String getParameterValue(Object obj) {
        String value = null;
        if (obj instanceof String) {
            value = "'" + obj.toString() + "'";
        } else if (obj instanceof Date) {
            DateFormat formatter = DateFormat.getDateTimeInstance(DateFormat.DEFAULT, DateFormat.DEFAULT, Locale.CHINA);
            value = "'" + formatter.format(new Date()) + "'";
        } else {
            if (obj != null) {
                value = obj.toString();
            } else {
                value = "";
            }

        }
        return value;
    }

    public static String showSql(Configuration configuration, BoundSql boundSql) {
        Object parameterObject = boundSql.getParameterObject();
        List<ParameterMapping> parameterMappings = boundSql.getParameterMappings();
        String sql = boundSql.getSql().replaceAll("[\\s]+", " ");
        if (parameterMappings.size() > 0 && parameterObject != null) {
            TypeHandlerRegistry typeHandlerRegistry = configuration.getTypeHandlerRegistry();
            if (typeHandlerRegistry.hasTypeHandler(parameterObject.getClass())) {
                sql = sql.replaceFirst("\\?", getParameterValue(parameterObject));

            } else {
                MetaObject metaObject = configuration.newMetaObject(parameterObject);
                for (ParameterMapping parameterMapping : parameterMappings) {
                    String propertyName = parameterMapping.getProperty();
                    if (metaObject.hasGetter(propertyName)) {
                        Object obj = metaObject.getValue(propertyName);
                        sql = sql.replaceFirst("\\?", getParameterValue(obj));
                    } else if (boundSql.hasAdditionalParameter(propertyName)) {
                        Object obj = boundSql.getAdditionalParameter(propertyName);
                        sql = sql.replaceFirst("\\?", getParameterValue(obj));
                    }
                }
            }
        }
        return sql;
    }

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

    public void setProperties(Properties properties0) {
        this.properties = properties0;
    }
}

裝逼永無止境 P.S 別太浪