11

我以下列方式使用 SimpleJdbcTemplate 和 MapSqlParameterSource:

MapSqlParameterSource parameterSource = new MapSqlParameterSource();
parameterSource.addValue("typeId", typeId, Types.BIGINT);

List<Long> ids = _jdbcTemplate.query(_selectIdByParameters, new EntityIdRowMapper(), parameterSource);

typeId( which is a Long) isnull时,查询如下所示:

SELECT id FROM XXX WHERE typeId = null

而我希望它会产生

SELECT id FROM XXX WHERE typeId IS NULL

我已经报告了这个问题,得到的回应是

您必须根据查询参数提供适当的 SQL 语句。

因此,我的代码中充斥着空检查。

有没有更优雅的方式来处理发送到的空参数SimpleJdbcTemplate

4

1 回答 1

7

他们有一个观点 - 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”,但我认为这不是一个选项。

于 2009-07-21T09:47:23.137 回答