1. 前言
配置SQL打印一方面可以了解到每个操作都具体执行的什么 SQL 语句, 另一方面通过打印执行耗时,也可以提前发现一些慢 SQL,提前做好优化, 省得 DBA 公开处刑。注意,生产环境不推荐打印执行 SQL,会有数据泄漏风险,仅推荐本地开发使用。
2. 添加依赖
在父项目的 pom.xml 文件中,声明 p6spy 依赖的版本号:
<properties> // 省略... <p6spy.version>3.9.1</p6spy.version> </properties> <dependencyManagement> <dependencies> // 省略... <dependency> <groupId>p6spy</groupId> <artifactId>p6spy</artifactId> <version>${p6spy.version}</version> </dependency>
</dependencies> </dependencyManagement>
|
然后在具体的业务模块中的 pom.xml 文件中,引入该依赖:
<dependency> <groupId>p6spy</groupId> <artifactId>p6spy</artifactId> </dependency>
|
3. 添加配置
3.1 修改 application-dev.yml 配置文件
spring: datasource: driver-class-name: com.p6spy.engine.spy.P6SpyDriver url: jdbc:p6spy:mysql://127.0.0.1:3306/weblog?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&useSSL=false&zeroDateTimeBehavior=convertToNull ...
|
注意:
- driver-class-name : 修改为 p6spy 提供的驱动类;
- url : 修改为前缀为 jdbc:p6spy 跟着冒号,后面对应数据库连接地址;
3.2 添加 p6spy 配置文件
然后在模块的 resources 目录下添加 spy.properties 配置文件:

配置文件内容如下:
modulelist=com.baomidou.mybatisplus.extension.p6spy.MybatisPlusLogFactory,com.p6spy.engine.outage.P6OutageFactory
logMessageFormat=com.baomidou.mybatisplus.extension.p6spy.P6SpyLogger
appender=com.baomidou.mybatisplus.extension.p6spy.StdoutLogger
deregisterdrivers=true
useprefix=true
excludecategories=info,debug,result,commit,resultset
dateformat=yyyy-MM-dd HH:mm:ss
outagedetection=true
outagedetectioninterval=2
|
4. 生产环境不要启用 p6spy
p6spy 组件请勿在生产环境使用,因为有性能损耗,推荐仅本地 dev 环境开发开启使用。 最终做法是,在 applcation-prod.yml 文件不启用 p6spy 组件,我们将 application-dev.yml 的数据库配置复制一份到 application-prod.yml 文件中,注意,要将驱动、前缀恢复正常,内容如下:
driver-class-name: com.mysql.cj.jdbc.Driver url: jdbc:mysql://127.0.0.1:3306/windblog?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&useSSL=false&zeroDateTimeBehavior=convertToNull username: root password: 123456
|
5. 结语
本文给大家介绍了在项目用使用 Mybatis Plus 持久层框架时,如何通过 p6spy 组件完整的打印 SQL 语句,以及执行耗时,此功能对于本地开发定位问题、杜绝慢查询都非常有帮助。