项目场景:

记录日常开发过程中 Mybatis 调试 SQL 语句,涉及一些敏感信息或者是因为报错原因,Mybatis 中执行的 SQL无法正常输出到控制台, 导致定位困难


问题描述

执行 SQL 查询语句,控制台打印“缺失 SELECT 关键字”, 由于目前项目组使用的 Mybatis 经过前人的一些封装,当SQL出错时,返回控制台是“”一个空串,无法清晰看到错误SQL语句的打印

“缺失 SELECT 关键字” 等错误关键字的输出

定位执行的SQL语句:找到 MappedStatement

public BoundSql getBoundSql(Object parameterObject) {
    BoundSql boundSql = sqlSource.getBoundSql(parameterObject);
    List<ParameterMapping> parameterMappings = boundSql.getParameterMappings();
    if (parameterMappings == null || parameterMappings.size() <= 0) {
      boundSql = new BoundSql(configuration, boundSql.getSql(), parameterMap.getParameterMappings(), parameterObject);
    }

    // check for nested result maps in parameter mappings (issue #30)
    for (ParameterMapping pm : boundSql.getParameterMappings()) {
      String rmId = pm.getResultMapId();
      if (rmId != null) {
        ResultMap rm = configuration.getResultMap(rmId);
        if (rm != null) {
          hasNestedResultMaps |= rm.hasNestedResultMaps();
        }
      }
    }

    return boundSql;
  }

Mybatis 的底层都会把 Mapper.xml 配置文件中的SQL 标签转化为基于 JDBC 执行的语句, boundSql 变量可以看到完整的 SQL 语句

更多推荐

Mybatis 调试查看执行的 SQL 语句