crmepham
crmepham

Reputation: 4740

Java Jdbctemplate query for list with named parameter and row mapper?

I am attempting to implement a Jdbctemplate query method that will take a named parameter map and a row mapper as additional arguments.

So far I have the following:

    final SqlParameterSource namedParameters = new MapSqlParameterSource().addValue("searchTerm", "%" + text + "%");
List<Map<String, String>> result = (List<Map<String, String>>)jdbcTemplate.queryForList(query, namedParameters, (ResultSet rs) ->
{
    List<Map<String, String>> rows = new ArrayList<>();
    while (rs.next())
    {
        Map<String, String> row = new HashMap<>();
        for (int x = 0, j = queryColumns.length; x < j; x++) {
            row.put(queryColumns[x], rs.getString(queryColumns[x]));
        }
        rows.add(row);
    }
    return rows;
});

return result;

This gives me the following error:

Error:(67, 83) java: no suitable method found for queryForList(java.lang.String,org.springframework.jdbc.core.namedparam.SqlParameterSource,(ResultSet[...]ws; }) method org.springframework.jdbc.core.JdbcTemplate.queryForList(java.lang.String,java.lang.Class) is not applicable (cannot infer type-variable(s) T (actual and formal argument lists differ in length)) method org.springframework.jdbc.core.JdbcTemplate.queryForList(java.lang.String,java.lang.Object[],int[],java.lang.Class) is not applicable....

Is it possible to do this kind of query using Jdbctemplate, and how do I go about it?

Upvotes: 0

Views: 7626

Answers (1)

gigermocas
gigermocas

Reputation: 190

Named parameters are supported through NamedParameterJdbcTemplates. You could use something like:

final Map<String, Object> namedParameters = Collections.singletonMap("searchTerm", "%" + text + "%");
List<Map<String, String>> result = new NamedParameterJdbcTemplate(jdbcTemplate).query(query, namedParameters, (rs, rowNum) ->
{
    Map<String, String> row = new HashMap<>();
    for (int x = 0, j = queryColumns.length; x < j; x++) {
        row.put(queryColumns[x], rs.getString(queryColumns[x]));
    }
    return row;
});

return result;

Upvotes: 2

Related Questions