mybatis-plus配置控制台打印完整带参数SQL语句

问题背景

通常我们开发的时候,需要联合控制台和Navicat/PLSQL等工具进行语句的拼接检查,如果只是输出了一堆???,那么将极大降低我们的效率。因此我们需要输出完整的SQL语句以便调试。

Update

解决方案(StdOutImpl)

请注意: 部分朋友反馈不生效,估计跟引入的包有一定关系,druid+mybatis-plus-boot-starter 就亲测有用。请检查是否有log4j相关实现类。

如果是application.yml

#by zhengkai.blog.csdn.net
#mybatis-plus配置控制台打印完整带参数SQL语句
mybatis-plus:
  configuration:
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl

如果是application.properties,添加:

#mybatis-plus配置控制台打印完整带参数SQL语句
mybatis-plus.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl

Mybatis内置的日志工厂提供日志功能,具体的日志实现有以下几种方式:

  • SLF4J
  • Apache Commons Logging
  • Log4j 2
  • Log4j
  • JDK logging
  • no logging

具体选择哪个日志实现由MyBatis的LogFactory内置日志工厂确定。它会使用最先找到的(按上文列举的顺序查找)。 如果一个都未找到,日志功能就会被禁用。

    static {
        tryImplementation(LogFactory::useSlf4jLogging);
        tryImplementation(LogFactory::useCommonsLogging);
        tryImplementation(LogFactory::useLog4J2Logging);
        tryImplementation(LogFactory::useLog4JLogging);
        tryImplementation(LogFactory::useJdkLogging);
        tryImplementation(LogFactory::useNoLogging);
    }

不少应用服务器的classpath中已经包含Commons Logging,如Tomcat和WebShpere, 所以MyBatis会把它作为具体的日志实现。

记住这点非常重要。这意味着,在诸如 WebSphere的环境中——WebSphere提供了Commons Logging的私有实现,你的Log4J配置将被忽略。

这种做法不免让人悲摧,MyBatis怎么能忽略你的配置呢?事实上,因Commons Logging已经存 在,按优先级Log4J自然就被忽略了!

控制台输出

--- [ XNIO-1 task-12] c.s.cms.controller.IndexController       : username-admin-password-123456-****
Creating a new SqlSession
SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@708e9ffd] was not registered for synchronization because synchronization is not active
--- [ XNIO-1 task-12] com.alibaba.druid.pool.DruidDataSource   : {dataSource-1} inited
JDBC Connection [com.alibaba.druid.proxy.jdbc.ConnectionProxyImpl@62b13210] will not be managed by Spring
==>  Preparing: select * from user t where t.user_code='admin' and t.password='123456' 
==> Parameters: 
<==    Columns: user_id, user_code, create_date, modify_date, user_name, password, status, role_id, department_id, major_id, classes_id, year
<==        Row: 1, admin, 2020-02-15 22:14:32, 2020-02-18 23:38:51, Moshow K ZHENG, 123456, 1, 9, 1, 13, 113, 2020
<==      Total: 1
Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@708e9ffd]

解决方案(手写MybatisPlusOutImpl)

配置文件

mybatis-plus:
  configuration:
#    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
#    改为自己写的
    log-impl: com.softdev.system.config.MybatisPlusOutImpl

java类 MybatisPlusOutImpl

package com.softdev.system.config;

import org.apache.ibatis.logging.Log;
/**
 * @Description MybatisPlusOutImpl,直接使用控制台输出日志
 * @Author zhengkai.blog.csdn.net
 **/
public class MybatisPlusOutImpl implements Log {
    public MybatisPlusOutImpl(String clazz) {
        System.out.println("MybatisPlusOutImpl::"+clazz);
    }

    public boolean isDebugEnabled() {
        return true;
    }

    public boolean isTraceEnabled() {
        return true;
    }

    public void error(String s, Throwable e) {
        System.err.println(s);
        e.printStackTrace(System.err);
    }

    public void error(String s) {
        System.err.println("MybatisPlusOutImpl::"+s);
    }

    public void debug(String s) {
        System.out.println("MybatisPlusOutImpl::"+s);
    }

    public void trace(String s) {
        System.out.println("MybatisPlusOutImpl::"+s);
    }

    public void warn(String s) {
        System.out.println("MybatisPlusOutImpl::"+s);
    }
}

解决方案(LOG-DEBUG模式)

# 在application.yml 中增加配置,指定 mapper 文件所在的包,进入DEBUG模式
logging:
  level:
    com.baomidou.example.mapper: debug

官方解决方案p6spy(不建议)

查看p6spy最新版本 ,请注意,该方案为侵入式的JDBC级方案。

pom.xml引入

<!-- https://mvnrepository.com/artifact/p6spy/p6spy -->
<dependency>
    <groupId>p6spy</groupId>
    <artifactId>p6spy</artifactId>
    <version>3.9.1</version>
</dependency>

这是yaml版本,还没试过,待我实验一下.

spring:
  datasource:
    driver-class-name: com.p6spy.engine.spy.P6SpyDriver
    url: jdbc:p6spy:h2:mem:test
    ...

这是官方提供的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
  • 60
    点赞
  • 121
    收藏
    觉得还不错? 一键收藏
  • 33
    评论
### 回答1: 在MyBatis-Plus开启SQL打印可以通过在配置文件中设置log4j或者logback的日志级别来实现。具体步骤如下: 1. 在pom.xml文件中添加log4j或者logback的依赖。 2. 在配置文件中添加log4j或者logback的配置,设置日志级别为DEBUG。 3. 在MyBatis-Plus配置文件中添加如下配置: ``` mybatis-plus: configuration: log-impl: org.apache.ibatis.logging.stdout.StdOutImpl ``` 这样就可以在控制台输出SQL语句了。 ### 回答2: Mybatis-Plus是一款基于Mybatis的快速开发框架,它对Mybatis进行了封装和增强,简化了Mybatis的使用,提高了开发效率。在开发过程中,我们往往需要打印SQL语句以便于调试和优化,下面介绍如何在Mybatis-Plus开启SQL打印。 1. 配置文件中添加日志输出配置 在application.yml或application.properties配置文件中添加如下日志输出配置,其中logLevel可以设置为debug或trace。 logging: level: com.baomidou.mybatisplus.core.conditions: debug #mybatis-plus的condition日志输出级别 com.baomidou.mybatisplus.core.parser: debug #mybatis-plus的解析日志输出级别 com.baomidou.mybatisplus.core.MybatisConfiguration: debug #mybatis的配置日志输出级别 2. 改变Mybatis-Plus日志框架为Log4j2 在pom.xml文件中添加如下依赖,将Mybatis-Plus日志框架改为Log4j2。 <dependency> <groupId>org.apache.logging.log4j</groupId> <artifactId>log4j-slf4j-impl</artifactId> </dependency> 3. 使用Mybatis-Plus的Interceptor Mybatis-Plus提供了一个Interceptor接口,通过实现该接口可以在SQL执行前后进行拦截,并打印SQL语句。 在Mybatis-Plus配置类中添加如下配置: @Configuration public class MybatisPlusConfig { @Bean public ISqlInjector sqlInjector() { return new LogicSqlInjector(); } @Bean public PaginationInterceptor paginationInterceptor() { return new PaginationInterceptor(); } @Bean public PerformanceInterceptor performanceInterceptor() { PerformanceInterceptor performanceInterceptor = new PerformanceInterceptor(); performanceInterceptor.setMaxTime(30000); return performanceInterceptor; } @Bean public MybatisPlusInterceptor mybatisPlusInterceptor() { MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor(); interceptor.addInnerInterceptor(new Interceptor() { @Override public void beforeExecute(StatementHandler statementHandler, Connection connection, Integer integer) { BoundSql boundSql = statementHandler.getBoundSql(); String sql = boundSql.getSql(); System.out.println("SQL: " + sql); } @Override public void afterExecute(StatementHandler statementHandler, Connection connection, Integer integer, Throwable throwable) { } @Override public void afterClose(StatementHandler statementHandler, Connection connection, Boolean aBoolean) { } }); return interceptor; } } 以上为Mybatis-Plus开启SQL打印的三种方法,任选其一即可。实际开发中,可以根据项目需求选择最恰当的方法。 ### 回答3: MyBatis-Plus是MyBatis的增强工具,在实际开发中,开启SQL打印是一件非常重要的事情。开启SQL打印可以方便地查看和调试MyBatis-Plus所生成的SQL语句,从而更好地优化程序性能。 MyBatis-Plus提供了两种方法来开启SQL打印: 1.在application.yml或application.properties文件中添加如下配置: ``` mybatis-plus: configuration: log-impl: org.apache.ibatis.logging.stdout.StdOutImpl ``` 该配置的作用是将MyBatis-Plus日志输出控制台,包括SQL语句参数。在控制台中可以看到类似如下的输出: ``` DEBUG [main] : ==> Preparing: SELECT * FROM user WHERE name = ? DEBUG [main] : ==> Parameters: test(String) ``` 可以清晰地看到MyBatis-Plus所生成的SQL语句参数。 2.在MyBatis的XML配置文件中添加如下配置: ``` <configuration> <settings> <setting name="logImpl" value="STDOUT_LOGGING"/> </settings> </configuration> ``` 该配置的作用是开启MyBatis的日志输出,也包括SQL语句参数。在控制台中可以看到类似如下的输出: ``` DEBUG [main] - ==> Preparing: SELECT * FROM user WHERE name = ? DEBUG [main] - ==> Parameters: test(String) ``` 可以发现,该配置输出与第一种方法的输出基本相同。 总的来说,开启SQL打印可以方便地查看和调试MyBatis-Plus所生成的SQL语句,有助于优化程序性能。在实际开发中,应该根据具体情况选择合适的配置方法。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 33
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值