Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass multiple named parameters to Spring JdbcTemplate?

I have following code in a Spring Dao which works just fine -

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 -

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?

like image 755
Monika Michael Avatar asked Apr 13 '12 05:04

Monika Michael


People also ask

How does JdbcTemplate select multiple columns?

List<Map<String, Object>> rows = jdbcTemplate. queryForList("SELECT name, middle, family FROM table"); Every Map in this List represents a row in the returned query, the key represents the column name, and the value is the value of that column for that row.

Which is faster JPA or JdbcTemplate?

JdbcTemplate will most likely be faster when talking about pure query execution, because a JPA implementation will do more stuff: Parse JPQL (assuming you are using that) creating a SQL query out of that. executing it.


1 Answers

use this.

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

instead of this.

new MapSqlParameterSource(":restaurantId", restaurantId)
    .addValue(":userId", userId);
like image 112
erimerturk Avatar answered Sep 24 '22 11:09

erimerturk