1. 程式人生 > >MyBatis SQL 在控制檯列印

MyBatis SQL 在控制檯列印

mybatis 怎麼列印執行的sql?

查看了官方文件,跟蹤了mybatis原始碼發現有兩種方式:

方法一、在mybatis配置的xml中<configuration>標籤下新增

<settings>
    <setting name="logImpl" value="STDOUT_LOGGING" />
</settings>

sql列印成控制檯

==>  Preparing: select FIELD_VALUE,CATE_CODE from GOODS_CATEGORY_DICT_MAPPING 
==> Parameters
:
<== Columns: FIELD_VALUE, CATE_CODE <== Row: 22001, V1030011001001 //..... <== Total: 27

方法二、在log4j/logback/logck4j2中新增我們專案包路徑mapper為debug

<logger name="com.hh.sns.goods" level="DEBUG" additivity="false">
        <appender-ref ref="STDOUT"/>
</logger>

sql通過DEBUG在控制檯列印效果

2018-03-29 15:29:44.757 DEBUG c.h.s.g.b.m.G.selectAll [main] -==>  Preparing: select FIELD_VALUE,CATE_CODE from GOODS_CATEGORY_DICT_MAPPING 
2018-03-29 15:29:44.774 DEBUG c.h.s.g.b.m.G.selectAll [main] -==> Parameters: 
2018-03-29 15:29:44.792 DEBUG c.h.s.g.b.m.G.selectAll [main] -<==      Total: 27

mybatis日誌列印原始碼:org.apache.ibatis.logging.jdbc.ConnectionLogger

 public Object invoke(Object proxy, Method method, Object[] params)
      throws Throwable {
    try {
      //....... 
      if ("prepareStatement".equals(method.getName())) {
        if (isDebugEnabled()) {//是否列印日誌判斷
          debug(" Preparing: " + removeBreakingWhitespace((String) params[0]), true);
        }        
        PreparedStatement stmt = (PreparedStatement) method.invoke(connection, params);
        stmt = PreparedStatementLogger.newInstance(stmt, statementLog, queryStack);
        return stmt;
      } //.........
    } catch (Throwable t) {
      throw ExceptionUtil.unwrapThrowable(t);
    }
  }