就我而言,我必须使用LinkedHashMap
来保持按position
字段排序的查询结果。
来自 JavaDoc:
LinkedHashMap:“这个链表定义了迭代顺序,这通常是键插入映射的顺序(插入顺序)。请注意,如果将键重新插入映射,则插入顺序不受影响。”
HashMap:“此类不保证地图的顺序;特别是,它不保证顺序会随着时间的推移保持不变”。
提示:使用该方法消除了对对象getOrDefault
的额外检查。nullable
public List<BucketDto> findAll() {
var sql = """
SELECT
b.uuid bucket_uuid, b.position bucket_position, b.name bucket_name,
c.uuid card_uuid, c.position card_position, c.name card_name
FROM bucket AS b
LEFT JOIN card AS c ON c.bucket_id = b.id
ORDER BY b.position ASC, c.position ASC
""";
return jdbcTemplate.query(sql, rs -> {
Map<Double, BucketDto> resultMap = new LinkedHashMap<>();
while (rs.next()) {
var position = rs.getDouble("bucket_position");
var bucketDto = resultMap.getOrDefault(position, new BucketDto(
UUID.fromString(rs.getString("bucket_uuid")),
position,
rs.getString("bucket_name")));
if (Optional.ofNullable(rs.getString("card_uuid")).isPresent()) {
bucketDto.addCard(new CardDto(
UUID.fromString(rs.getString("card_uuid")),
rs.getDouble("card_position"),
rs.getString("card_name")));
}
resultMap.put(position, bucketDto);
}
return new ArrayList<>(resultMap.values());
});
}