mybatis学习之路----打印sql语句

时间:2024-10-05 07:18:58

点滴记载,点滴进步,愿自己更上一层楼。

用mybatis执行数据库操作仅仅能看到执行结果,如果想看到执行的sql语句怎么办。

查阅mybatis官方文档找到了解决方法。

官方文档传送门

配置什么的很简单,用的log4j打印,当然参照官方文档还有好几种方法,具体自弄。这里仅作记录只用。

配置很简单,将log4j架包加入到classpath里。

maven配置。

  1. <dependency>
  2. <groupId>log4j</groupId>
  3. <artifactId>log4j</artifactId>
  4. <version>1.2.17</version>
  5. </dependency>
非maven项目只需要将jar添加到项目中即可。

添加到source根目录。

# Global logging configuration
log4=ERROR, stdout
# MyBatis logging configuration...
#log4.test.dao=DEBUG
log4.dynamic=DEBUG
#log4=TRACE
# Console output...
log4=4
log4=4
log4=%5p [%t] - %m%n
其中关键的地方是
=DEBUG

是固定的,dynamic为你的的namespace

如果我的xml中的namespace为dynamic

  1. <?xml version="1.0" encoding="UTF-8" ?>
  2. <!DOCTYPE mapper
  3. PUBLIC "-////DTD Mapper 3.0//EN"
  4. "/dtd/">
  5. <!-- namespace命名空间,跟java的package类似,避免sql id重复,
  6. 有了这个命名空间,别的xml中的sql的id可以跟这个重复,并且 namespace不能省略,不能为空,不用接口开发,此处可以随意写-->
  7. <mapper namespace="dynamic">
  8. <resultMap id="userMap" type="">
  9. <id column="id" property="id"/>
  10. <result column="username" property="username"/>
  11. <result column="password" property="password"/>
  12. <result column="create_date" property="createDate"/>
  13. </resultMap>
  14. <!--if 标签使用类似html的C标签的if -->
  15. <select id="selectUseIf" parameterType="" resultMap="userMap">
  16. select * from t_user where
  17. <if test="id != null and id != ''">
  18. id=#{id}
  19. </if>
  20. <if test="username != null and username != ''">
  21. and username like concat('%',#{username},'%')
  22. </if>
  23. <if test="password != null and password != ''">
  24. and password=#{password}
  25. </if>
  26. </select>
  27. </mapper>
配置完成。现在运行测试即可看到运行的sql语句

------------------------------------------------------------------------------------------------------------------------------

DEBUG [main] - ==>  Preparing: select * from t_user where id=? and username like concat('%',?,'%') 
DEBUG [main] - ==> Parameters: 28(Integer), xiao(String)
DEBUG [main] - <==      Total: 1

-------------------------------------------------------------------------------------------------------------------------------
记录到此结束。