Reputation: 1083
How do I query for a List of Integers using namedParameterJdbcTemplate? I tried following this template, it is not working below .
https://stackoverflow.com/a/40417349/15435022
String customerName = "JOE";
MapSqlParameterSource customerParameters = new MapSqlParameterSource();
customerParameters.addValue("CustomerName", customerName);
private static final String query = "SELECT Customer_Id From dbo.Customers WHERE Customer_Name = :CustomerName";
List<Integer> data = namedParameterJdbcTemplate.queryForList(query, Integer.class);
Error: Cannot resolve method 'queryForList(java.lang.String, java.lang.Class<java.lang.Integer>)'
Upvotes: 2
Views: 3257
Reputation: 105
As mentioned in the docs queryForList Method have following implementations available:
queryForList(String sql, Map<String,?> paramMap)
.queryForList(String sql, Map<String,?> paramMap, Class<T> elementType)
queryForList(String sql, SqlParameterSource paramSource)
queryForList(String sql, SqlParameterSource paramSource, Class<T> elementType)
None of these implementations matches the parameters used in the given implementation. Thus, we end up with this error:
Error: Cannot resolve method 'queryForList(java.lang.String, java.lang.Class<java.lang.Integer>)'
The key idea behind passing a Map or ParameterSource is to have a dynamic query where we can put in values later on.
Eg:
String query = "Select :columnName from table";
Map<String,String> map = new HashMap<>();
map.put("columnName", "userName");
When this map is passed along with the query String, internally it is used to replace placeholders with the values from the map.
There are two ways you can fix this:
This is not the best way of fixing the problem is definitely not recommended for a production code. But, this can be used if there is no placeholder in the query string. Code:
List<Integer> data = namedParameterJdbcTemplate.queryForList(query, null, Integer.class);
You already have a MapSqlParameterSource called customerParameters in your code. Simply pass it while calling queryForList() Code:
List<Integer> data = namedParameterJdbcTemplate.queryForList(query, customerParameters, Integer.class);
Upvotes: 2