MyBatis 拦截器 - 统计sql执行信息

更多MyBatis实战内容,请参考:MyBatis - 实战指南

背景

记录insert/update操作执行的sql语句、执行耗时、影响行数等。

实现方法

@Intercepts({
        @Signature(type = Executor.class, method = "update", args = {MappedStatement.class, Object.class})
})
public class SqlInfoInterceptor implements Interceptor {
    private static final Logger LOGGER = LoggerFactory.getLogger("MyBatis");
    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        MappedStatement mappedStatement = (MappedStatement) invocation.getArgs()[0];
        Object parameter = invocation.getArgs()[1];
        Configuration configuration = mappedStatement.getConfiguration();
        Object target = invocation.getTarget();
        StatementHandler handler = configuration.newStatementHandler((Executor) target, mappedStatement,
                parameter, RowBounds.DEFAULT, null, null);
        //记录SQL
        BoundSql boundSql = handler.getBoundSql();
        //记录耗时
        long start = System.currentTimeMillis();
        //执行真正的方法
        Object result = invocation.proceed();
        long end = System.currentTimeMillis();
        //记录影响行数
        int affectedRows = Integer.valueOf(Integer.parseInt(result.toString()));
        //记录时间

        LOGGER.info("executed times: {}, sql: {}, affected rows: {}, time cost: {} ms",
                new Date(), boundSql.getSql(), affectedRows, end - start);

        return result;
    }

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

    @Override
    public void setProperties(Properties properties) {

    }
}

你可能感兴趣的:(MyBatis 拦截器 - 统计sql执行信息)