我想记录sql语句的执行时间。为此,我使用拦截器插件。但是它只“捕获”外部语句并打印执行整个语句所需的组合时间,包括@Result
中包含的子查询。为什么它不会单独记录所有语句,是否有任何解决方案?
以下是重现我的场景的代码:
ADAO:
@Select({
"select * from a",
"where id = #{id,jdbcType=INTEGER}"
})
@Results({
@Result(column="id", property="id", jdbcType=JdbcType.INTEGER, id=true),
@Result(column="id", property="bs", javaType=List.class, many=@Many(fetchType=FetchType.EAGER, select = "org.BDao.selectByAId")),
@Result(column="id", property="cs", javaType=List.class, many=@Many(fetchType=FetchType.EAGER, select = "org.CDao.selectByAId"))
})
A selectByPrimaryKey(Integer id);
BDAO:
@Select({
"select * from b",
"where a_id = #{aId,jdbcType=INTEGER}"
})
@Results({
...
})
List<B> selectByAId(Integer aId);
CDao:
@Select({
"select * from c",
"where a_id = #{aId,jdbcType=INTEGER}"
})
@Results({
...
})
List<C> selectByAId(Integer aId);
拦截器:
@Intercepts({ @Signature(type = Executor.class, method = "query", args = { MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class }) })
public class LogTimeQueryExecutePlugin implements Interceptor {
static int MAPPED_STATEMENT_INDEX = 0;
static int PARAMETER_INDEX = 1;
static int ROWBOUNDS_INDEX = 2;
static int RESULT_HANDLER_INDEX = 3;
static Logger logger = LoggerFactory.getLogger(LogTimeQueryExecutePlugin.class);
public Object intercept(Invocation invocation) throws Throwable {
long start = System.currentTimeMillis();
Object proceed = invocation.proceed();
MappedStatement ms = (MappedStatement) invocation.getArgs()[MAPPED_STATEMENT_INDEX];
logger.info("Execution time "+ms.getId()+" : "+(System.currentTimeMillis() - start)+" ms");
return proceed;
}
public Object plugin(Object target) {
return Plugin.wrap(target, this);
}
public void setProperties(Properties properties) {
}
}
记录:
执行时间org.ADao.selectByPrimaryKey:59033 ms