Monday, June 20, 2011

Spring JdbcTemplate to retrieve List and Map

org.springframework.jdbc.core.JdbcTemplate used to perform query for specific result through out some query parameters. Some of the basic queries like query, queryForList, QueryForObject as the common understandings of the methods name. A query or queryForList method returns a list of desired rows but queryForMap returns only a single row where all the column names are key of the Map.
To retrieve a list, org.springframework.jdbc.core.RowMapper can be used along with java.sql.ResultSet. A sample code is like,

List sampleClassList = 
      jdbcTemplate.query(query, new Object[]{parameters.....},
     new RowMapper() {
  public Object mapRow(ResultSet rs, int rowNum) throws SQLException {
  SampleClass sampleClass = new SampleClass();
  sampleClass.setValue1(rs.getString("column1"));
  sampleClass.setValue2(rs.getString("column2"));
  return sampleClass;
 }
});

In most of the cases developers convert a retrieved list to their desired Map later by manipulating the list. The basic reason behind is a map will not contain duplicate values as key but to a list data can be redundant. Its also possible to get a Map where one column as key and other as value of the map. org.springframework.jdbc.core.ResultSetExtractor can be used for customize results like Map. The following sample code can do this thing. Its really a very good option if one do not want to have duplicate value in a specific column. Its easier to make that thing a key.

Map map = (Map)jdbcTemplate.query(query, new Object[]{parameters....},
     new ResultSetExtractor() {
       public Object extractData(ResultSet rs) throws SQLException {
       Map map = new LinkedHashMap();
       while (rs.next()) {
         String col1 = rs.getString("col1");
         String col2 = rs.getString("col2");
         map.put(col1, col2);
       }
      return map;
   };
});

No comments:

Post a Comment

Chitika