17

Can I use queryForMap if there are multiple rows returned by the query.

For a single row, the below code works fine.

public Map<String, Object> retrieveMultipleRowsColumns(String deptName){
    return jdbcTemplate.queryForMap("SELECT DEPT_ID,DEPT_NAME FROM DEPT WHERE DEPT_NAME = ?", deptName);
}

How to modify this for multiple rows?

Rajat
  • 2,467
  • 2
  • 29
  • 38
user182944
  • 7,897
  • 33
  • 108
  • 174

3 Answers3

27

I know this is really old, but there is a much simpler way to do this if you're looking for a map.

Simply implement the ResultSetExtractor interface to define what type you want to return. Below is an example of how to use this. You'll be mapping it manually, but for a simple map, it should be straightforward.

jdbcTemplate.query("select string1,string2 from table where x=1", new ResultSetExtractor<Map>(){
    @Override
    public Map extractData(ResultSet rs) throws SQLException,DataAccessException {
        HashMap<String,String> mapRet= new HashMap<String,String>();
        while(rs.next()){
            mapRet.put(rs.getString("string1"),rs.getString("string2"));
        }
        return mapRet;
    }
});

This will give you a return type of Map that has multiple rows (however many your query returned) and not a list of Maps. You can view the ResultSetExtractor docs here: http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/jdbc/core/ResultSetExtractor.html

Erica Kane
  • 3,137
  • 26
  • 36
Brian Beech
  • 1,055
  • 9
  • 13
25

Use queryForList see the javadoc for full details. It returns List<Map<String,Object>>

public List<Map<String, Object>> retrieveMultipleRowsColumns(String deptName){
    return jdbcTemplate.queryForList("SELECT DEPT_ID,DEPT_NAME FROM DEPT WHERE DEPT_NAME = ?", deptName);
}
John Farrelly
  • 7,289
  • 9
  • 42
  • 52
-3
public <T> List<T> queryForList(String sql,
                            Class<T> elementType,
                            Object... args)
                 throws DataAccessException

Description copied from interface: JdbcOperations Query given SQL to create a prepared statement from SQL and a list of arguments to bind to the query, expecting a result list. The results will be mapped to a List (one entry for each row) of result objects, each of them matching the specified element type.

Specified by:queryForList in interface JdbcOperations , Parameters:sql - SQL query to execute elementType - the required type of element in the result list (for example, Integer.class)args - arguments to bind to the query (leaving it to the PreparedStatement to guess the corresponding SQL type); may also contain SqlParameterValue objects which indicate not only the argument value but also the SQL type and optionally the scale Returns:a List of objects that match the specified element type Throws: DataAccessException - if the query failsSee Also:JdbcOperations.queryForList(String, Class), SingleColumnRowMapper

Divya MV
  • 2,021
  • 3
  • 31
  • 55