mybatis 打印 sql

作者: rejoice001 | 来源:发表于2017-12-05 23:26 被阅读2次

    在mybatis的configuration中增加setting配置

    <settings>
            <setting name="logPrefix" value="dao."/>
    </settings>
    

    然后增加配置

    <logger name="dao" level="DEBUG"/>
    

    源码解析:

    ConnectionLogger
    public Object invoke(Object proxy, Method method, Object[] params)
          throws Throwable {
        try {
          if (Object.class.equals(method.getDeclaringClass())) {
            return method.invoke(this, params);
          }    
          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;
          }
    

    其中的isDebugEnabled()指的是

    protected boolean isDebugEnabled() {
        return statementLog.isDebugEnabled();
    }
    

    注意这里的statementLog,看SimpleExecutor的prepareStatement(handler, ms.getStatementLog());

    public <E> List<E> doQuery(MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, BoundSql boundSql) throws SQLException {
        Statement stmt = null;
        try {
          Configuration configuration = ms.getConfiguration();
          StatementHandler handler = configuration.newStatementHandler(wrapper, ms, parameter, rowBounds, resultHandler, boundSql);
          stmt = prepareStatement(handler, ms.getStatementLog());
          return handler.<E>query(stmt, resultHandler);
        } finally {
          closeStatement(stmt);
        }
      }
    

    这个statementLog是ms.getStatementLog()而来的。而MappedStatement的StatementLog

    String logId = id;
     if (configuration.getLogPrefix() != null) logId = configuration.getLogPrefix() + id;
     mappedStatement.statementLog = LogFactory.getLog(logId);
    

    这里可以看到,logPrefix决定了所有log前缀,所以只需要配置logPrefix就行了

    相关文章

      网友评论

        本文标题:mybatis 打印 sql

        本文链接:https://www.haomeiwen.com/subject/ojbhixtx.html