I have following code -
getNamedParameterJdbcTemplate().queryForList("SELECT id FROM emp WHERE age=:age",
new MapSqlParameterSource("age", 19))
How can I get the final query sent to Mysql after parameter replacement? Is there something like -
getNamedParameterJdbcTemplate(query, paramSource).gimmeTheFinalQuery()
Incredibly verbose but working solution is -
ParsedSql parsedSql = NamedParameterUtils.parseSqlStatement("SELECT id FROM emp WHERE age=:age");
SqlParameterSource source = new MapSqlParameterSource("age", 19);
String finalQuery = new PreparedStatementCreatorFactory(NamedParameterUtils.substituteNamedParameters(parsedSql,
source), NamedParameterUtils.buildSqlTypeArray(parsedSql, source))
.newPreparedStatementCreator(NamedParameterUtils.buildValueArray(parsedSql, source, null))
.createPreparedStatement(getConnection()).toString();
finalQuery = finalQuery.substring(finalQuery.indexOf(":") + 1, finalQuery.length());
System.out.println(finalQuery);
Output -
SELECT id FROM emp WHERE age=19
This can be wrapped into a utility class -
public class SpringQueryParser {
Connection con;
public SpringQueryParser(Connection con) {
this.con = con;
}
public String getFinalQuery(String query, SqlParameterSource source) throws SQLException {
ParsedSql parsedSql = NamedParameterUtils.parseSqlStatement(query);
String finalQuery = new PreparedStatementCreatorFactory(NamedParameterUtils.substituteNamedParameters(parsedSql,
source), NamedParameterUtils.buildSqlTypeArray(parsedSql, source))
.newPreparedStatementCreator(NamedParameterUtils.buildValueArray(parsedSql, source, null))
.createPreparedStatement(con).toString();
return finalQuery.substring(finalQuery.indexOf(":") + 1, finalQuery.length()).trim();
}
}
And then called conveniently as such -
new SpringQueryParser(getConnection()).getFinalQuery("SELECT id FROM emp WHERE age=:age",
new MapSqlParameterSource("age", 19))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With