点滴记载,点滴进步,愿自己更上一层楼。
用mybatis执行数据库操作仅仅能看到执行结果,如果想看到执行的sql语句怎么办。
查阅mybatis官方文档找到了解决方法。
官方文档传送门
配置什么的很简单,用的log4j打印,当然参照官方文档还有好几种方法,具体自弄。这里仅作记录只用。
配置很简单,将log4j架包加入到classpath里。
maven配置。
-
<dependency>
-
<groupId>log4j</groupId>
-
<artifactId>log4j</artifactId>
-
<version>1.2.17</version>
-
</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
-
<?xml version="1.0" encoding="UTF-8" ?>
-
<!DOCTYPE mapper
-
PUBLIC "-////DTD Mapper 3.0//EN"
-
"/dtd/">
-
<!-- namespace命名空间,跟java的package类似,避免sql id重复,
-
有了这个命名空间,别的xml中的sql的id可以跟这个重复,并且 namespace不能省略,不能为空,不用接口开发,此处可以随意写-->
-
<mapper namespace="dynamic">
-
-
<resultMap id="userMap" type="">
-
<id column="id" property="id"/>
-
<result column="username" property="username"/>
-
<result column="password" property="password"/>
-
<result column="create_date" property="createDate"/>
-
</resultMap>
-
-
<!--if 标签使用类似html的C标签的if -->
-
<select id="selectUseIf" parameterType="" resultMap="userMap">
-
select * from t_user where
-
<if test="id != null and id != ''">
-
id=#{id}
-
</if>
-
<if test="username != null and username != ''">
-
and username like concat('%',#{username},'%')
-
</if>
-
<if test="password != null and password != ''">
-
and password=#{password}
-
</if>
-
</select>
-
-
</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
-------------------------------------------------------------------------------------------------------------------------------
记录到此结束。