αƞjiβ
αƞjiβ

Reputation: 3246

Return result as Map from JdbcTemplate

I was wondering if there is easy way to generate Map for the results from the query using JdbcTemplate. I have a query which returns two columns so I want to make map from the result directly.

SQL query:

SELECT id, name FROM mytable WHERE somecol='someval';

Expected map:

{123,ABC},{456,DEF} .... {890, XYZ}

Upvotes: 2

Views: 9543

Answers (2)

tostao
tostao

Reputation: 3048

I think that you can use this instead of JDBCTemplate. And use method queryForMap. And your param put like this:

SqlParameterSource namedParameters = new MapSqlParameterSource("somecol",someval);

Upvotes: 0

woemler
woemler

Reputation: 7169

Yes, it is possible to return a map of column-name: column-value pairs using JdbcTemplate, but what you have described in your question is not an actual map.

public List<Map<String, Object>> getList() {
    return this.jdbcTemplate.queryForList("SELECT id, name FROM mytable");
}

Would return:

[{'id': 123, 'name': 'ABC'}, {...}, ... ]

See the official documentation for more.

Upvotes: 2

Related Questions