如何将多条记录的结果放入 map int JDBC 模板?

How to get result of multiple records into map int JDBC Template?

我正在使用 queryForList 来获取结果集的数组列表,如下例所示:

List<Student> studentsList = null;
String sql = "SELECT * FROM [student]";
try {
    studentsList = jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(Student.class));
} catch (EmptyResultDataAccessException e) {
}
return (ArrayList<Student>) studentsList;

现在我想将此列表的结果直接从查询中获取到 keyobject 的映射中。

有什么想法吗?

使用 queryForMap 而不是 query。如果您需要按列名映射,这将解决您的问题。

文档:queryForMap

您不可能从这样的查询中获得您的 Map。您将需要操纵从 jdbcTemplate.query 返回的 List,以便它为您提供所需的 Map,每个键都是学生的 ID:

Map<Integer, Student> studentMap = new HashMap<Integer, Student>();
for (Student student : studentsList) {
    studentMap.put(student.getId(), student);
}

如果您使用的是 java 8,则可以使用 Collector:

Map<Integer, Student> result = studentsList.stream().collect(Collectors.toMap(Student::getId, Function.identity()));