如何让SpringBoot工程在log/控制台中实时打印MyBatis执行的SQL语句

示例工程下载:https://files.cnblogs.com/files/heyang78/myBank_mybatis_oracle_junit_210905_1453.rar

在使用MyBatis的SpringBoot工程中,有时需要打印Mapper接口类诸函数访问DB时用到的SQL语句,如下面的Mapper:

package com.hy.mybank.mapper;

import java.util.List;

import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;

import com.hy.mybank.Entity.Student;

@Mapper
public interface StudentMapper {
    @Select("select * from student where id=#{id}")
    Student findById(@Param("id") int id);
    
    @Select("select * from student")
    List<Student> findAll();
}

由于接口中没有方法体,所以通常的在代码里写输出的手段就失效了。

但也不要着急,就是一句话设置的事情,实现步骤就是在application.properties中书写

logging.level.com.hy.mybank.mapper.StudentMapper=debug

这样一行,其中com.hy.mybank.mapper.StudentMapper即需要打印SQL语句的接口类。

 

之后执行起来,就能看到SQL输出了,示例如下:

2021-09-05 14:48:11.226  INFO 6304 --- [           main] com.hy.mybank.MyBankApplicationTests     : Started MyBankApplicationTests in 3.055 seconds (JVM running for 5.651)
2021-09-05 14:48:11.904 DEBUG 6304 --- [           main] c.h.m.mapper.StudentMapper.findById      : ==>  Preparing: select * from student where id=?
2021-09-05 14:48:12.035 DEBUG 6304 --- [           main] c.h.m.mapper.StudentMapper.findById      : ==> Parameters: 1(Integer)
2021-09-05 14:48:12.236 DEBUG 6304 --- [           main] c.h.m.mapper.StudentMapper.findById      : <==      Total: 1
2021-09-05 14:48:12.274 DEBUG 6304 --- [           main] c.h.mybank.mapper.StudentMapper.findAll  : ==>  Preparing: select * from student
2021-09-05 14:48:12.275 DEBUG 6304 --- [           main] c.h.mybank.mapper.StudentMapper.findAll  : ==> Parameters: 
2021-09-05 14:48:12.278 DEBUG 6304 --- [           main] c.h.mybank.mapper.StudentMapper.findAll  : <==      Total: 2

相对于旧版本的SQL与参数分离,当前工程的SQL是一起输出了,这点做得不错。

--2020-04-29初稿--

2021年9月5日修订

参考文档:https://www.cnblogs.com/mww-NOTCOPY/p/10990492.html

posted @ 2020-04-29 15:08  逆火狂飙  阅读(1214)  评论(0编辑  收藏  举报
生当作人杰 死亦为鬼雄 至今思项羽 不肯过江东