How I can get proper return type of List<Map<String, Object>> mapList = jdbctemplate.queryForList(query)); Where my query is “SELECT * FROM table_name;”.
Can anyone help me?
Advertisement
Answer
You can use the following snippet to get the required map from the list:
List<Map<String, Object>> mapList = jdbctemplate.queryForList(query)); return mapList.stream().collect(Collectors.toMap(k -> (Integer) k.get("id"), k -> (String) k.get("name")));
mapList.stream().collect(Collectors.toMap(k -> (Integer) k.get(“id”), k -> (String) k.get(“name”))); this is used to extract the exact data alone from the whole object that you are selecting using your query (SELECT * FROM table_name). Try this out.
A simpler way for getting a map alone is by implementing the ResultSetExtractor interface to define what type you want to return you can get a Map as a result. Below is an example of how to use this. You’ll be mapping it manually,
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 and not a list of Maps. For learning more about the result set extractor Click Here