如何将多个命名参数传递给Spring JdbcTemplate?

莫妮卡·迈克尔(Monika Michael):

我在Spring Dao中有以下代码,它很好用-

Object args[] = { userId, restaurantId };
int userOrderCount = getJdbcTemplate()
    .queryForInt(
         "SELECT COUNT(orderid) FROM orders WHERE useridfk_order = ? AND restaurantidfk_order = ?", 
         args
    );

但是,如果我决定对查询使用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)
    );

我收到此例外-

org.springframework.dao.InvalidDataAccessApiUsageException: No value supplied for the SQL parameter 'userId': No value registered for key 'userId'.

我知道这句金句“如果它没有破裂,请不要修复”。

但是,我还是忍不住想知道为什么会这样吗?

特殊土耳其:

用这个。

new MapSqlParameterSource("restaurantId", restaurantId)
    .addValue("userId", userId);

而不是这个。

new MapSqlParameterSource(":restaurantId", restaurantId)
    .addValue(":userId", userId);

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章