mybaitplus打印SQL语句
时间: 2025-06-03 13:16:03 浏览: 10
### MyBatis-Plus 打印 SQL 语句的配置方法
为了使 MyBatis-Plus 能够在控制台打印完整的 SQL 语句,可以通过多种方式实现这一需求。以下是几种常见的配置方法:
#### 方法一:通过 `application.yml` 或 `application.properties` 配置文件启用日志
可以在 Spring Boot 的配置文件中设置 MyBatis-Plus 的日志实现类为标准输出日志工具。具体配置如下所示[^3]:
```yaml
mybatis-plus:
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
```
或者,在 `application.properties` 文件中添加以下内容:
```properties
mybatis-plus.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl
```
此方法简单易用,适合快速验证 SQL 是否正常执行。
---
#### 方法二:使用 MyBatis 自带的日志框架 Log4j 或 SLF4J
如果项目已经集成了更高级别的日志管理工具(如 Log4j 或 SLF4J),可以调整这些工具的级别来显示 SQL 日志。例如,对于 Logback 来说,可在 `logback.xml` 中增加以下配置[^2]:
```xml
<logger name="com.baomidou.mybatisplus" level="DEBUG"/>
<logger name="org.mybatis.spring" level="DEBUG"/>
```
上述配置会将 MyBatis 和 MyBatis-Plus 的相关操作记录到 DEBUG 级别下,从而展示详细的 SQL 输出。
---
#### 方法三:自定义拦截器实现 SQL 执行时间和参数打印
除了简单的日志配置外,还可以通过编写自定义拦截器的方式捕获并打印 SQL 语句及其参数。这种方式更加灵活,能够满足复杂场景下的需求。下面是一个基于 MyBatis 拦截器的例子[^1]:
创建一个拦截器类,并注册到 MyBatis-Plus 的全局配置中:
```java
import com.baomidou.mybatisplus.extension.plugins.inner.InterceptorIgnoreHelper;
import net.sf.jsqlparser.parser.CCJSqlParserUtil;
import net.sf.jsqlparser.statement.Statement;
import java.sql.Connection;
import java.util.Properties;
public class SqlInterceptor implements Interceptor {
@Override
public boolean intercept(Invocation invocation) throws Throwable {
Object[] args = invocation.getArgs();
MappedStatement ms = (MappedStatement) args[0];
Object parameter = args[1];
BoundSql boundSql = ms.getBoundSql(parameter);
String sql = boundSql.getSql();
try {
Statement parsedStatement = CCJSqlParserUtil.parse(sql); // 解析SQL语法树
System.out.println("Parsed SQL: " + parsedStatement.toString());
} catch (Exception e) {
System.err.println("Failed to parse SQL: " + sql);
}
long start = System.currentTimeMillis();
Object result = invocation.proceed(); // 继续执行原生逻辑
long end = System.currentTimeMillis();
System.out.println("Execution Time: " + (end - start) + "ms");
return true;
}
}
```
随后将其加入到 MyBatis-Plus 的插件列表中:
```java
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor() {
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
interceptor.addInnerInterceptor(new SqlInterceptor()); // 注册自定义拦截器
return interceptor;
}
```
这种方法不仅可以打印 SQL,还能附加更多元数据信息,比如耗时统计等。
---
#### 方法四:借助 P6Spy 插件完成精细化监控
P6Spy 是一款专门用于数据库访问层的监控工具,支持对 SQL 进行实时跟踪和分析。集成该工具后,可轻松获取带有实际运行参数的完整 SQL 语句。
##### 步骤说明:
1. **引入依赖**
修改项目的 Maven 或 Gradle 构建脚本,添加 P6Spy 的依赖项:
```xml
<!-- Maven -->
<dependency>
<groupId>p6spy</groupId>
<artifactId>p6spy</artifactId>
<version>3.9.1</version>
</dependency>
```
2. **修改 JDBC URL**
将原有的数据库连接地址替换为指向 P6Spy 的代理路径。例如:
```properties
spring.datasource.url=jdbc:p6spy:mysql://localhost:3306/your_database_name
```
3. **新增 spy.properties 文件**
创建一份名为 `spy.properties` 的资源文件,指定其行为模式:
```properties
module.log=com.p6spy.engine.spy.P6SpyFactory
appender=com.p6spy.engine.spy.appender.Slf4JLogger
realdriver=com.mysql.cj.jdbc.Driver
logMessageFormat=com.p6spy.engine.spy.appender.CustomLineFormat
customLogMessageFormat=%executionTime ms - %sql
includeCategories=info,debug,result,batch,statement
excludeCategories=log
```
以上步骤完成后即可看到经过格式化处理后的 SQL 记录。
---
### 总结
MyBatis-Plus 提供了丰富的选项让用户自由选择最适合自己的 SQL 打印方案。无论是基础的日志配置还是深入定制化的拦截机制都能很好地服务于不同的应用场景。
阅读全文
相关推荐


















