【问题标题】:BoundSql does not substitute values of parameter in SQL statement in MyBatisBoundSql 不替换 MyBatis 中 SQL 语句中的参数值
【发布时间】:2015-03-31 10:30:32
【问题描述】:

我需要在 MyBatis 中打印生成的 SQL 但不执行它。我已经尝试了来自主题的程序:Can I use MyBatis to generate Dynamic SQL without executing it?。除了一件事,它有效。有 '?'符号而不是打印的 SQL 中的数据。所以它看起来就像这样:

insert into testTable (name, data) values (?,?)

这是我正在使用的代码:

波乔

public class TestPojo {
  Integer id;
  String name;
  String data;
  //Ommitted getters and setters
}

public interface TestDAO {
   public void insertData(TestPojo p);
}

映射器.xml

<mapper namespace="package.TestDAO">

<resultMap id="testResult" type="TestPojo" >
    <id column="id" property="id" jdbcType="INTEGER"/>
    <result column="name" property="name" jdbcType="VARCHAR"/>
    <result column="data" property="data" jdbcType="VARCHAR"/>
</resultMap> 

<insert id="insertData" parameterType="TestPojo">
    insert into testTable (name, data) values (#{name},#{data})
</insert>

</mapper>

MyBatis 配置 xml

<configuration>
<!--misc settings -->
<settings>
    <setting name="lazyLoadingEnabled" value="false" /> 
</settings>

<typeAliases>
    <typeAlias type="package.TestPojo" alias="TestPojo" />
</typeAliases>
<!--XML mappers -->    
<mappers>
    <mapper resource="database/TestMapper.xml" />
</mappers>
</configuration>

最后我使用以下代码获得了 SQL:

Configuration configuration = sqlSessionFactory.getConfiguration();
MappedStatement ms = configuration.getMappedStatement("insertData");
BoundSql boundSql = ms.getBoundSql(new TestPojo("Jeff", "The funny guy"));
System.out.println("SQL: \n" + boundSql.getSql());

我做错了什么?

【问题讨论】:

    标签: java mysql spring mybatis


    【解决方案1】:

    好吧,仍然不知道为什么它不起作用。所以我写了一个简单的方法来完成这项工作。

    public void createSQLReportItem(MappedStatement ms) {
        BoundSql boundSql = ms.getBoundSql(originalRec);
        List<ParameterMapping> params = boundSql.getParameterMappings();
    
        finalSql = boundSql.getSql();
        finalSql = finalSql.replaceAll("\\s", " ");
        finalSql = finalSql.replaceAll("[ ]{2,}", " ");
    
        for (ParameterMapping pm : params) {
            if (paramMapping.containsKey(pm.getProperty())) {
                finalSql = finalSql.replaceFirst("\\?", paramMapping.get(pm.getProperty()));
            }
        }
    }
    

    其中originalRec 是语句的参数,paramMapping 是我自己的包含映射-参数名称-> 值的映射。我知道这不是最好的解决方案,但它确实有效..

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-06-04
      • 1970-01-01
      • 2013-09-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多