目标:打印DAO方法中sql和执行的时间
一种方式是去实现Mybatis的拦截器Interceptor ,比较麻烦;
这里介绍一种比较简单的实现方式;
1、如何打印sql?
配置文件加这个可以打印出com.zhenhui.ids.busi.watch包下执行的sql
logging.level.com.zhenhui.ids.busi.watch=debug
2、如何打印sql执行时间
com.zhenhui.ids.busi.watch 包下有多个子包,大部分子包下有DAO结尾的类,或者是Dao结尾
新建AOP切面类:MapperAspect
package com.zhenhui.ids.busi.watch.config;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import java.util.Arrays;
@Aspect
@Component
@Slf4j
public class MapperAspect {
@Pointcut("execution(* com.zhenhui.ids.busi.watch..*DAO.*(..))|| " +
"execution(* com.zhenhui.ids.busi.watch..*Dao.*(..))) "
)
private void pointCutMethod() {
}
@Around("pointCutMethod()")
public Object doAround(ProceedingJoinPoint pjp) {
long begin = System.nanoTime();
Object obj = null;
try {
obj = pjp.proceed();
}
catch (Throwable throwable) {
log.info("执行异常");
}
long end = System.nanoTime();
log.info("调用Mapper方法:{},参数:{},\n耗时:{}毫秒",
pjp.getSignature().toString(), Arrays.toString(pjp.getArgs()), (end - begin) / 1000000);
return obj;
}
}