2015-03-31 61 views
1

我需要在MyBatis中打印生成的SQL,但不執行它。我已經嘗試過主題:Can I use MyBatis to generate Dynamic SQL without executing it?。它的作品除了一件事。有 '?'符號而不是打印SQL中的數據。所以它看起來就像這樣:BoundSql不會替代MyBatis中SQL語句中參數的值

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

這裏是我使用的代碼:

POJO的

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

DAO

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

Mapper.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()); 

我做錯了嗎?

回答

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是我自己的地圖方含映射 - PARAM_NAME - >值。我知道這不是最好的解決方案,但它的工作原理..