简体   繁体   中英

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?

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM