我以简单的方式使用SimpleJdbcTemplate和MapsqlParameterSource:
MapsqlParameterSource parameterSource = new MapsqlParameterSource(); parameterSource.addValue("typeId",typeId,Types.BIGINT); List<Long> ids = _jdbcTemplate.query(_selectIdByParameters,new EntityIdRowMapper(),parameterSource);
当typeId(这是一个Long)为空时,查询的查询方式如下:
SELECT id FROM XXX WHERE typeId = null
而我期望它产生
SELECT id FROM XXX WHERE typeId IS NULL
我有@L_301_0@,答复是这样的
You will have to provide the appropriate sql statement based on your query parameters.
因此我的代码散布着空白的检查.
是否有更优雅的方式处理发送给SimpleJdbcTemplate的空参数?
解决方法
他们有一点 – JdbcTemplate不是一个sql解释器,它只是替换你的占位符.
我建议您使用实用程序方法构造您的子句,并将其与查询字符串相连:
String createNullCheckedClause(String column,Object value) { String operator = (value == null ? "is" : "="); return String.format("(%s %s ?)",column,operator); } ... String query = "select * from table where " + createNullCheckedClause("col",x);
不是很漂亮或者,也许您可以配置MysqL允许“= NULL”,但我不认为这是一个选项.