您的位置:首页 > 博客中心 > 数据库 >

Mybatis3中用log4j跟踪SQL语句

时间:2022-03-13 23:46

在开发过程中,打印SQL语句应该是一个非常有用的功能。

下面介绍如何在Mybatis3中开启打印SQL语句的功能。

Mybatis内置的日志工厂提供日志功能,具体的日志实现有以下几种方式:

    log4j.rootLogger=error, Console log4j.logger.com.zhuchao.test.dao=debug #Console log4j.appender.Console=org.apache.log4j.ConsoleAppender log4j.appender.Console.layout=org.apache.log4j.PatternLayout log4j.appender.Console.layout.ConversionPattern=%d [%t] %-5p [%c] - %m%n

    其中com.zhuchao.test.dao则是Mapper类所在的包名,若是想指定某个Mapper输出SQL语句

    还可以实现更细粒度的配置,比如log4j.logger.com.zhuchao.test.dao.PersonMapper=debug

    再细一点,还可以指定到具体的一条sql语句,比如log4j.logger.com.zhuchao.test.dao.PersonMapper.selectById=debug

    若想对Mapper.xml文件进行日志记录,只需要根据namespace来就可以了。

    一般项目中mapper.xml和mapper类都是一一对应的,所以两者配置都一样~

    值得注意的是,debug的日志级别,只会打印SQL语句,参数,以及影响的记录条数

    2014-09-14 00:49:10,078 [http-8080-3] DEBUG [com.zhuchao.test.BasecodeMapper.selectByExample] - ==>  Preparing: select * from basecode WHERE ( cls = ? ) 
    2014-09-14 00:49:10,078 [http-8080-3] DEBUG [com.zhuchao.test.BasecodeMapper.selectByExample] - ==> Parameters: level(String)
    2014-09-14 00:49:10,079 [http-8080-3] DEBUG [com.zhuchao.test.BasecodeMapper.selectByExample] - <==      Total: 2

    若还想看到所有的执行结果,可以将日志级别设置为trace:

    2014-09-14 00:49:10,078 [http-8080-3] DEBUG [com.zhuchao.test.BasecodeMapper.selectByExample] - ==>  Preparing: select * from basecode WHERE ( cls = ? ) 
    2014-09-14 00:49:10,078 [http-8080-3] DEBUG [com.zhuchao.test.BasecodeMapper.selectByExample] - ==> Parameters: level(String)
    2014-09-14 00:49:10,079 [http-8080-3] TRACE [com.zhuchao.test.BasecodeMapper.selectByExample] - <==    Columns: cls, id, code, name, description, seq
    2014-09-14 00:49:10,079 [http-8080-3] TRACE [com.zhuchao.test.BasecodeMapper.selectByExample] - <==        Row: level, 1, level2, 等级2, 等级2, 0
    2014-09-14 00:49:10,079 [http-8080-3] TRACE [com.zhuchao.test.BasecodeMapper.selectByExample] - <==        Row: level, 2, level1, 等级1, 等级1, 0
    2014-09-14 00:49:10,079 [http-8080-3] DEBUG [com.zhuchao.test.BasecodeMapper.selectByExample] - <==      Total: 2

热门排行

今日推荐

热门手游