百度360必应搜狗淘宝本站头条
当前位置:网站首页 > IT技术 > 正文

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

wptr33 2024-12-23 14:04 12 浏览

前言

在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 新增)
  • 该插件有性能损耗,不建议生产环境使用。

相关推荐

【推荐】一款开源免费、美观实用的后台管理系统模版

如果您对源码&技术感兴趣,请点赞+收藏+转发+关注,大家的支持是我分享最大的动力!!!项目介绍...

Android架构组件-App架构指南,你还不收藏嘛

本指南适用于那些已经拥有开发Android应用基础知识的开发人员,现在想了解能够开发出更加健壮、优质的应用程序架构。首先需要说明的是:AndroidArchitectureComponents翻...

高德地图经纬度坐标批量拾取(高德地图批量查询经纬度)

使用方法在桌面上新建一个index.txt文件,把下面的代码复制进去保存,再把文件名改成index.html保存,双击运行打开即可...

flutter系列之:UI layout简介(flutter ui设计)

简介对于一个前端框架来说,除了各个组件之外,最重要的就是将这些组件进行连接的布局了。布局的英文名叫做layout,就是用来描述如何将组件进行摆放的一个约束。...

Android开发基础入门(一):UI与基础控件

Android基础入门前言:...

iOS的布局体系-流式布局MyFlowLayout

iOS布局体系的概览在我的CSDN博客中的几篇文章分别介绍MyLayout布局体系中的视图从一个方向依次排列的线性布局(MyLinearLayout)、视图层叠且停靠于父布局视图某个位置的框架布局(M...

TDesign企业级开源设计系统越发成熟稳定,支持 Vue3 / 小程序

TDesing发展越来越好了,出了好几套组件库,很成熟稳定了,新项目完全可以考虑使用。...

WinForm实现窗体自适应缩放(winform窗口缩放)

众所周知,...

winform项目——仿QQ即时通讯程序03:搭建登录界面

上两篇文章已经对CIM仿QQ即时通讯项目进行了需求分析和数据库设计。winform项目——仿QQ即时通讯程序01:原理及项目分析...

App自动化测试|原生app元素定位方法

元素定位方法介绍及应用Appium方法定位原生app元素...

61.C# TableLayoutPanel控件(c# tabcontrol)

摘要TableLayoutPanel在网格中排列内容,提供类似于HTML元素的功能。TableLayoutPanel控件允许你将控件放在网格布局中,而无需精确指定每个控件的位置。其单元格...

想要深入学习Android性能优化?看完这篇直接让你一步到位

...

12个python数据处理常用内置函数(python 的内置函数)

在python数据分析中,经常需要对字符串进行各种处理,例如拼接字符串、检索字符串等。下面我将对python中常用的内置字符串操作函数进行介绍。1.计算字符串的长度-len()函数str1='我爱py...

如何用Python程序将几十个PDF文件合并成一个PDF?其实只要这四步

假定你有一个很无聊的任务,需要将几十个PDF文件合并成一个PDF文件。每一个文件都有一个封面作为第一页,但你不希望合并后的文件中重复出现这些封面。即使有许多免费的程序可以合并PDF,很多也只是简单的将...

Python入门知识点总结,Python三大数据类型、数据结构、控制流

Python基础的重要性不言而喻,是每一个入门Python学习者所必备的知识点,作为Python入门,这部分知识点显得很庞杂,内容分支很多,大部分同学在刚刚学习时一头雾水。...