加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

java – SimpleJdbcTemplate和null参数

发布时间:2020-12-15 00:58:06 所属栏目:Java 来源:网络整理
导读:我以简单的方式使用SimpleJdbcTemplate和MapSqlParameterSource: MapSqlParameterSource parameterSource = new MapSqlParameterSource();parameterSource.addValue("typeId",typeId,Types.BIGINT);ListLong ids = _jdbcTemplate.query(_selectIdByParamete
我以简单的方式使用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

我有reported this issue,答复是这样的

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”,但我不认为这是一个选项.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读