MyBatis 教程

👉 所有文章
文章列表 准备工作 回顾 JDBC 数据准备 查找id为1的用户信息 自定义连接池 不用MyBatis配置文件 查询密码为123的所有用户 如果Bean中成员变量和表中字段命名不一致 更多查询用户的方式 对查询结果排序 日志 添加、删除、修改数据 事务 动态SQL 一对一和一对多的实现 一对一和一对多的延迟加载 多对多的实现 分页查询 把SQL写在注解中 自动生成Mapper代码和映射XML mybatis generator 生成 select for update mybatis generator 支持数据版本号

MyBatis: 日志


我们可以通过配置,让mybatis打印出执行过程中的日志。

排序 中的示例 mybatis-demo-007 为例,log4j.properties 配置为:

log4j.rootLogger=INFO, stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n

我们只需要加一行:

log4j.logger.org.mybatis.mapper=TRACE

就可以打印出 mapper 包下所有 Mapper 接口中函数的执行日志。因为log4j.rootLogger=INFO,所以只会打印出INFO级别及以上级别的日志。为了看到更多日志,可以将其改成更低级别的DEBUG。最终如下:

log4j.rootLogger=DEBUG, stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n

# mapper 包下的所有接口的方法都会打日志,会打印不低于 DEBUG 级别的日志
log4j.logger.org.mybatis.mapper=TRACE

执行 Main 类中的以下代码:

@Test
public void test_01() throws IOException {
    SqlSession sqlSession = getSqlSession();
    UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
    List<User> userList = userMapper.findByPassword("123", "id asc");
    log.info("{}", userList);
}

输出如下:

DEBUG [main] - Logging initialized using 'class org.apache.ibatis.logging.slf4j.Slf4jImpl' adapter.
DEBUG [main] - PooledDataSource forcefully closed/removed all connections.
DEBUG [main] - PooledDataSource forcefully closed/removed all connections.
DEBUG [main] - PooledDataSource forcefully closed/removed all connections.
DEBUG [main] - PooledDataSource forcefully closed/removed all connections.
DEBUG [main] - Opening JDBC Connection
DEBUG [main] - Created connection 17037394.
DEBUG [main] - Setting autocommit to false on JDBC Connection [com.mysql.jdbc.JDBC4Connection@103f852]
DEBUG [main] - ==>  Preparing: select * from blog_db.user where password=? order by id asc 
DEBUG [main] - ==> Parameters: 123(String)
DEBUG [main] - <==      Total: 2
 INFO [main] - [User(id=1, name=letian, email=letian@111.com, password=123), User(id=2, name=xiaosi, email=xiaosi@111.com, password=123)]

本节示例代码在 mybatis-demo-008


( 本文完 )

文章目录