How to Get Map Collection using Spring Jdbc Template

I wanted to access Map collection using Spring JdbcTemplate, but the method jdbcTemplate.queryForMap(...) returns a single Map instance (i.e. Map with only one Entry). Here is how I proceeded to extract Map with multiple entries.


1. Define a MapExtracter class

public class MapExtractor implements ResultSetExtractor {

public Object extractData(ResultSet rs)
throws SQLException, DataAccessException {

Map map = new LinkedHashMap();

while (rs.next()) {
Integer key = rs.getInt("id");
String value = rs.getString("name");
map.put(key, value);
}
return map;
}
}


2. Use the MapExtracter class with a simple JdbcTemplate as follows:

Map map = (Map)getJdbcTemplate().query(
"SELECT id, name FROM business WHERE type_id=10",
new MapExtractor());

The returned map is a collection of multiple entries.

Comments

  1. Wonderful information.Jdbc is used to java beans i know the basics of java beans.It is for all to clearly express the java beans.

    java training in chennai

    ReplyDelete
  2. Pretty article! I found some useful information in your blog, it was awesome to read, thanks for sharing this great content to my vision, keep sharing.
    Regards,

    Core JAVA Training in Chennai | JAVA Training in Chennai

    ReplyDelete

Post a Comment