[java] How to get Map data using JDBCTemplate.queryForMap

How to load data from JDBCTemplate.queryForMap() and it returns the Map Interface.How the maintained the query data internally in map.I trying to load but i got below exception i.e., org.springframework.dao.IncorrectResultSizeDataAccessException: Incorrect result

Code:-

public List getUserInfoByAlll() {
    List profilelist=new ArrayList();
    Map m=new HashMap();
    m=this.jdbctemplate.queryForMap("SELECT userid,username  FROM USER");
    Set s=m.keySet();
    Iterator it=s.iterator();
    while(it.hasNext()){
        String its=(String)it.next();
        Object ob=(Object)m.get(its);
        log.info("UserDAOImpl::getUserListSize()"+ob);
    }
    return profilelist;
}

Plz help me

This question is related to java spring jdbctemplate

The answer is


I know this is really old, but this is the simplest way to query for 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-framework/docs/2.5.6/api/org/springframework/jdbc/core/ResultSetExtractor.html


You can do something like this.

 List<Map<String, Object>> mapList = jdbctemplate.queryForList(query));
    return mapList.stream().collect(Collectors.toMap(k -> (Long) k.get("userid"), k -> (String) k.get("username")));

Output:

 {
  1: "abc",
  2: "def",
  3: "ghi"
}

To add to @BrianBeech's answer, this is even more trimmed down in java 8:

jdbcTemplate.query("select string1,string2 from table where x=1", (ResultSet rs) -> {
    HashMap<String,String> results = new HashMap<>();
    while (rs.next()) {
        results.put(rs.getString("string1"), rs.getString("string2"));
    }
    return results;
});

Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to spring

Are all Spring Framework Java Configuration injection examples buggy? Two Page Login with Spring Security 3.2.x Access blocked by CORS policy: Response to preflight request doesn't pass access control check Failed to configure a DataSource: 'url' attribute is not specified and no embedded datasource could be configured ApplicationContextException: Unable to start ServletWebServerApplicationContext due to missing ServletWebServerFactory bean Failed to auto-configure a DataSource: 'spring.datasource.url' is not specified Spring Data JPA findOne() change to Optional how to use this? After Spring Boot 2.0 migration: jdbcUrl is required with driverClassName The type WebMvcConfigurerAdapter is deprecated No converter found capable of converting from type to type

Examples related to jdbctemplate

How to set up datasource with Spring for HikariCP? SQL state [99999]; error code [17004]; Invalid column type: 1111 With Spring SimpleJdbcCall how to query for a list<String> in jdbctemplate Jdbctemplate query for string: EmptyResultDataAccessException: Incorrect result size: expected 1, actual 0 How to get Map data using JDBCTemplate.queryForMap Spring JDBC Template for calling Stored Procedures Return Type for jdbcTemplate.queryForList(sql, object, classType) How to execute INSERT statement using JdbcTemplate class from Spring Framework Using prepared statements with JDBCTemplate How to execute IN() SQL queries with Spring's JDBCTemplate effectively?