Reputation: 81
I need to print generated SQL in MyBatis but without executing it. I have tried procedure from topic: Can I use MyBatis to generate Dynamic SQL without executing it?. It works except for one thing. There are '?' symbols instead of data in printed SQL. So it looks just like this:
insert into testTable (name, data) values (?,?)
Here is the code I am using:
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 config 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>
And finally I get SQL by using following code:
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());
What I am doing wrong?
Upvotes: 1
Views: 1736
Reputation: 81
Well, still don't know why it doesn't work. So I've written simple method which will do the job.
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()));
}
}
}
where originalRec
is parameter for the statement and paramMapping
is my own map containg mappings - param_name -> value. I know that it is not the best solution, but it works..
Upvotes: 1