项目配置是springboot + mybatis。
打印sql语句
application.properties配置文件中添加
mybatis.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl
打印sql执行时间
添加MapperAspect类
@Aspect
@Component
@Slf4j
public class MapperAspect {
@AfterReturning("execution(* com.myApp.bot.mapper.*Mapper.*(..))")
public void logServiceAccess(JoinPoint joinPoint){
// log.info("Completed: " + joinPoint);
}
@Pointcut("execution(* com.myApp.bot.mapper.*Mapper.*(..))")
private void pointCutMethod(){
}
@Around("pointCutMethod()")
public Object doAround(ProceedingJoinPoint pjp) throws Throwable{
long begin = System.nanoTime();
Object obj = pjp.proceed();
long end = System.nanoTime();
log.info("调用Mapper方法:{},参数:{},\n耗时:{}毫秒",
pjp.getSignature().toString(), Arrays.toString(pjp.getArgs()), (end - begin) / 1000000);
return obj;
}
}
代码中的com.myApp.bot.mapper.Mapper.(…))路径替换为你本地的Mapper文件路径。如下图:

实现效果


本文介绍了如何在SpringBoot+Mybatis项目中实现SQL语句的打印以及执行时间的记录。通过在`application.properties`中设置`mybatis.configuration.log-impl`为`StdOutImpl`来开启SQL日志,然后创建一个名为`MapperAspect`的切面类,使用AOP的`@AfterReturning`和`@Around`注解来记录并打印每个Mapper方法的执行时间和详细信息。这样可以帮助开发者优化数据库操作,提升应用性能。

被折叠的 条评论
为什么被折叠?



