gpt4 book ai didi

java - SimpleJdbcTemplate 和空参数

转载 作者:IT老高 更新时间:2023-10-28 13:47:18 25 4
gpt4 key购买 nike

我使用 SimpleJdbcTemplate 和 MapSqlParameterSource 的方式如下:

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

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

typeId (即 Long )为 null 时,查询如下所示:

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

关于java - SimpleJdbcTemplate 和空参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1157839/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com