MyBatis实战六之MyBatis-Plus开启SQL日志打印

MyBatis实战六之MyBatis-Plus开启SQL日志打印

经验文章nimo972025-01-07 11:52:2510A+A-

前言

在MyBatis-Plus中有三种方式打印SQL语句

1、在application.yml文件中添加mybatisplus的配置文件

2、在application.yml文件中使用log4j日志框架配置

3、使用P6spy插件

一、在application.yml文件中添加mybatisplus的配置文件

使用MyBatis-Plus自带的log-impl配置,可以在控制台打印出sql语句、执行结果的数据集、数据结果条数等详细信息,这种方法适合在调试的时候使用,因为这个展示的信息详细,更便于调试,查找问题进行优化。缺点就是如果执行的sql语句过多,则输出的日志就会很多。

application.yml 配置

mybatis-plus:
  configuration:
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl

单元测试代码

@RunWith(SpringRunner.class)
@SpringBootTest(classes = WebApplication.class)
public class SqlLogTest {
    @Resource
    private UserInfoDao userInfoDao;

    @Test
    public void update(){
        UserInfo userInfo = userInfoDao.selectById(1);
        userInfo.setAddress("北京");
        userInfoDao.updateById(userInfo);
    }
}

运行程序,打印日志如下:

Creating a new SqlSession
SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@1cd6b1bd] was not registered for synchronization because synchronization is not active
JDBC Connection [com.alibaba.druid.proxy.jdbc.ConnectionProxyImpl@55846997] will not be managed by Spring
==>  Preparing: SELECT id,nick_name,gender,type,is_vip,grade,address,create_time,version FROM user WHERE id=?
==> Parameters: 1(Integer)
<==    Columns: id, nick_name, gender, type, is_vip, grade, address, create_time, version
<==        Row: 1, 喜羊羊, 1, 1, 1, 3, 北京, 2024-01-18 00:00:00, 1
<==      Total: 1
Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@1cd6b1bd]
Creating a new SqlSession
SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@691541bc] was not registered for synchronization because synchronization is not active
JDBC Connection [com.alibaba.druid.proxy.jdbc.ConnectionProxyImpl@55846997] will not be managed by Spring
==>  Preparing: UPDATE user SET nick_name=?, gender=?, type=?, is_vip=?, grade=?, address=?, create_time=?, version=? WHERE id=? AND version=?
==> Parameters: 喜羊羊(String), 1(Integer), 1(Integer), 1(Integer), 3(Integer), 北京(String), 2024-01-18 00:00:00.0(Timestamp), 2(Integer), 1(Long), 1(Integer)
<==    Updates: 1
Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@691541bc]

二、在application.yml文件中使用log4j日志框架配置

使用这个方法可以在控制台或者日志文件中打印sql语句,这种方法比较适合在生产环境种使用,可以避免输出过多的无用信息,也可以使用日志级别来控制是否打印sql语句。

com.mysql.dao  #mapper层的包名

application.yml 配置

logging:
  level:
    com.mysql.dao: debug

运行以上单元测试,打印日志如下:

2024-04-03 15:02:47.422 DEBUG 36007 --- [           main] c.mysql.dao.user.UserInfoDao.selectById  : ==>  Preparing: SELECT id,nick_name,gender,type,is_vip,grade,address,create_time,version FROM user WHERE id=?
2024-04-03 15:02:47.477 DEBUG 36007 --- [           main] c.mysql.dao.user.UserInfoDao.selectById  : ==> Parameters: 1(Integer)
2024-04-03 15:02:47.516 DEBUG 36007 --- [           main] c.mysql.dao.user.UserInfoDao.selectById  : <==      Total: 1
2024-04-03 15:02:47.613 DEBUG 36007 --- [           main] c.mysql.dao.user.UserInfoDao.updateById  : ==>  Preparing: UPDATE user SET nick_name=?, gender=?, type=?, is_vip=?, grade=?, address=?, create_time=?, version=? WHERE id=? AND version=?
2024-04-03 15:02:47.624 DEBUG 36007 --- [           main] c.mysql.dao.user.UserInfoDao.updateById  : ==> Parameters: 喜羊羊(String), 1(Integer), 1(Integer), 1(Integer), 3(Integer), 北京(String), 2024-01-18 00:00:00.0(Timestamp), 3(Integer), 1(Long), 2(Integer)
2024-04-03 15:02:47.731 DEBUG 36007 --- [           main] c.mysql.dao.user.UserInfoDao.updateById  : <==    Updates: 1

三 、使用P6spy插件

可以在控制台中打印出sql语句,并且在控制台中将输出的sql中的?部分替换位真实运行的值,这种方法适合需要复制sql语句到数据库工具中直接执行的场景,也可以通过spyproperties文件来配置是否开启慢sql记录、慢sql记录标准的参数。该插件有性能损耗,不建议生产环境使用

引入依赖

	<dependency>
    <groupId>p6spy</groupId>
		<artifactId>p6spy</artifactId>
		<version>3.9.1</version>
	</dependency>

配置数据库

spring:
  datasource:
    type: com.alibaba.druid.pool.DruidDataSource
    dynamic:
      primary: user
      strict: false
      datasource:
        user:
          driver-class-name: com.p6spy.engine.spy.P6SpyDriver
          url: jdbc:p6spy:mysql://127.0.0.1:3306/test?zeroDateTimeBehavior=convertToNull&autoReconnect=true&generateSimpleParameterMetadata=true
          username: root
          password: yangyanping

配置spy.properties文件

#3.2.1以上使用
modulelist=com.baomidou.mybatisplus.extension.p6spy.MybatisPlusLogFactory,com.p6spy.engine.outage.P6OutageFactory
#3.2.1以下使用或者不配置
#modulelist=com.p6spy.engine.logging.P6LogFactory,com.p6spy.engine.outage.P6OutageFactory
# 自定义日志打印
logMessageFormat=com.baomidou.mybatisplus.extension.p6spy.P6SpyLogger
#日志输出到控制台
appender=com.baomidou.mybatisplus.extension.p6spy.StdoutLogger
# 使用日志系统记录 sql
#appender=com.p6spy.engine.spy.appender.Slf4JLogger
# 设置 p6spy driver 代理
deregisterdrivers=true
# 取消JDBC URL前缀
useprefix=true
# 配置记录 Log 例外,可去掉的结果集有error,info,batch,debug,statement,commit,rollback,result,resultset.
excludecategories=info,debug,result,commit,resultset
# 日期格式
dateformat=yyyy-MM-dd HH:mm:ss
# 实际驱动可多个
#driverlist=org.h2.Driver
# 是否开启慢SQL记录
outagedetection=true
# 慢SQL记录标准 2 秒
outagedetectioninterval=2

运行以上单元测试,打印日志如下:

2024-04-03 15:11:50.164 DEBUG 36178 --- [           main] c.mysql.dao.user.UserInfoDao.selectById  : ==>  Preparing: SELECT id,nick_name,gender,type,is_vip,grade,address,create_time,version FROM user WHERE id=?
2024-04-03 15:11:50.221 DEBUG 36178 --- [           main] c.mysql.dao.user.UserInfoDao.selectById  : ==> Parameters: 1(Integer)
 Consume Time:32 ms 2024-04-03 15:11:50
 Execute SQL:SELECT id,nick_name,gender,type,is_vip,grade,address,create_time,version FROM user WHERE id=1 

2024-04-03 15:11:50.300 DEBUG 36178 --- [           main] c.mysql.dao.user.UserInfoDao.selectById  : <==      Total: 1
2024-04-03 15:11:50.358 DEBUG 36178 --- [           main] c.mysql.dao.user.UserInfoDao.updateById  : ==>  Preparing: UPDATE user SET nick_name=?, gender=?, type=?, is_vip=?, grade=?, address=?, create_time=?, version=? WHERE id=? AND version=?
2024-04-03 15:11:50.372 DEBUG 36178 --- [           main] c.mysql.dao.user.UserInfoDao.updateById  : ==> Parameters: 喜羊羊(String), 1(Integer), 1(Integer), 1(Integer), 3(Integer), 北京(String), 2024-01-18 00:00:00.0(Timestamp), 4(Integer), 1(Long), 3(Integer)
 Consume Time:65 ms 2024-04-03 15:11:50
 Execute SQL:UPDATE user SET nick_name='喜羊羊', gender=1, type=1, is_vip=1, grade=3, address='北京', create_time='2024-01-18T00:00:00.000+0800', version=4 WHERE id=1 AND version=3

2024-04-03 15:11:50.438 DEBUG 36178 --- [           main] c.mysql.dao.user.UserInfoDao.updateById  : <==    Updates: 1

注意:

  • driver-class-name 为 p6spy 提供的驱动类
  • url 前缀为 jdbc:p6spy 跟着冒号为对应数据库连接地址
  • 打印出 sql 为 null,在 excludecategories 增加 commit
  • 批量操作不打印 sql,去除 excludecategories 中的 batch
  • 批量操作打印重复的问题请使用 MybatisPlusLogFactory (3.2.1 新增)
  • 该插件有性能损耗,不建议生产环境使用。

点击这里复制本文地址 以上内容由nimo97整理呈现,请务必在转载分享时注明本文地址!如对内容有疑问,请联系我们,谢谢!
qrcode

尼墨宝库 © All Rights Reserved.  蜀ICP备2024111239号-7