示例工程下載: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日修訂