I have following code in a Spring Dao which works just fine -
我在Spring Dao中有以下代码,它工作得很好
Object args[] = { userId, restaurantId };
int userOrderCount = getJdbcTemplate()
.queryForInt(
"SELECT COUNT(orderid) FROM orders WHERE useridfk_order = ? AND restaurantidfk_order = ?",
args
);
However if I decide to use NamedParameters for my query as follows -
但是,如果我决定为我的查询使用NamedParameters,如下所示
int userOrderCount = getNamedParameterJdbcTemplate()
.queryForInt(
"SELECT COUNT(orderid) FROM orders WHERE useridfk_order = :userId AND restaurantidfk_order = :restaurantId",
new MapSqlParameterSource(":restaurantId", restaurantId)
.addValue(":userId", userId)
);
I am getting this exception -
我有这个例外
org.springframework.dao.InvalidDataAccessApiUsageException: No value supplied for the SQL parameter 'userId': No value registered for key 'userId'.
I know the golden adage "Don't fix it if it ain't broken".
我知道那句金玉良言:“如果它没坏就不要修理它”。
But still, I can't help but wonder why this is happening?
但我还是忍不住想知道为什么会发生这种事?
1 个解决方案
#1
21
use this.
用这个。
new MapSqlParameterSource("restaurantId", restaurantId)
.addValue("userId", userId);
instead of this.
而不是这个。
new MapSqlParameterSource(":restaurantId", restaurantId)
.addValue(":userId", userId);
#1
21
use this.
用这个。
new MapSqlParameterSource("restaurantId", restaurantId)
.addValue("userId", userId);
instead of this.
而不是这个。
new MapSqlParameterSource(":restaurantId", restaurantId)
.addValue(":userId", userId);