mattsmith5
mattsmith5

Reputation: 1083

How to query for a single column in NamedJdbcTemplate?

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

Answers (1)

Akash Yadav
Akash Yadav

Reputation: 105

Why code gives an error

As mentioned in the docs queryForList Method have following implementations available:

  1. queryForList(String sql, Map<String,?> paramMap).
  2. queryForList(String sql, Map<String,?> paramMap, Class<T> elementType)
  3. queryForList(String sql, SqlParameterSource paramSource)
  4. 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 idea behind passing missing parameter

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.

How to fix the code

There are two ways you can fix this:

  1. Just pass null

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);
  1. Create and pass an empty Map or SqlParameterSource

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

Related Questions