Java 番石榴多重映射到响应模型的映射结果
在我的web服务应用程序中,以下模型用作统计信息的UI契约,其中在给定日期,我需要提供接受的Java 番石榴多重映射到响应模型的映射结果,java,spring,jdbc,guava,spring-jdbc,Java,Spring,Jdbc,Guava,Spring Jdbc,在我的web服务应用程序中,以下模型用作统计信息的UI契约,其中在给定日期,我需要提供接受的数量、拒绝的数量等的摘要: @Data public class StatusResponse { private LocalDate processedDate; private int accepted; private int rejected; private int failed; private int other; } “我的数据库查询”返回总结的结
数量、拒绝的数量等的摘要:
@Data
public class StatusResponse {
private LocalDate processedDate;
private int accepted;
private int rejected;
private int failed;
private int other;
}
“我的数据库查询”返回总结的结果,如下所示:
date status groupStatus count
2020-01-01 ACC Accepted 3
2020-01-22 RJCT Rejected 47
2020-01-22 NM Other 1
2020-01-23 NIY Failed 55
我有一个枚举状态
:
public enum Status{
ACCEPTED("Accepted"),
REJECTED("Rejected"),
OTHER("Other"),
FAILED("Failed");
private final String text;
Status (final String text) {
this.text = text;
}
}
在我的repository类中,我将状态摘要查询并检索到GuavaMultiMap
对象中,其中键是date,值是状态及其计数的EnumMap
:
public Multimap<LocalDate, EnumMap<Status, Integer>> statusSummary(final Request search) {
return this.namedParameterJdbcTemplate.query(this.QUERY,
new MapSqlParameterSource()
.addValue("processedDate", search.getProcessedDate()),
rs -> {
final Multimap<LocalDate, EnumMap<Status, Integer>> statusMap = ArrayListMultimap.create();
while (rs.next()) {
final EnumMap<Status, Integer> groupedStatusCount = new EnumMap<>(Status.class);
groupedStatusCount.put(fromValue(rs.getString("groupStatus")), rs.getInt("count"));
statusMap.put(rs.getDate("date").toLocalDate(), groupedStatusCount);
}
return statusMap;
}
);
}
我的问题和我正在努力完成的内容:
如何将statusMap
的结果映射到StatusResponse
并提供每个日期的摘要。所以上面的StatusResponse
是这样的:
{
"processedDate": [
2020,
1,
23
],
"accepted": 2,
"rejected": 0,
"failed": 0,
"other": 27,
"date": "2020-01-23T00:00:00"
}
我正在使用Java8,希望得到一些帮助,我如何通过流操作和以函数式方式使用groupBy
来实现这一点
此外,我需要进一步分组,将今天之前的任何内容分组到今天,将今天之后的任何内容分组到今天+1
谢谢您可以尝试以下方法。摘要可以存储在Map
中,并使用来自Jackson的JsonAnyGetter
注释在根级别展开。这将从响应中删除摘要字段,并将内部值放在根级别
@Data
@Builder
public class StatusResponse {
private LocalDate processedDate;
@JsonAnyGetter
private Map<Status, Integer> summary;
}
输出应该是这样的
[{
"processedDate":"2020-01-23",
"FAILED":3,
"ACCEPTED":2
}]
注意:若数据库返回所有状态,那个么即使值为零,它也会包含在响应中。所以,要使所有状态字段都响应,只需使它们都是multimap的一部分
您可以进一步探索自定义序列化程序来微调日期格式 根据消息约定,我不能在响应中包含摘要
标记,它需要包含接受
、拒绝
等的单个值,即使它们不是db返回的元素。您能更新您的答案以包含所有字段吗?@M06H如果您使数据库返回所有状态,即使值为零,它也将被包含。
List<StatusResponse> responseList = data.entries().stream()
.map(entry -> {
Map<Status, Integer> summary = entry.getValue().entries().stream()
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (a, b) -> b));
return StatusResponse.builder()
.processedDate(entry.getKey())
.summary(summary)
.build();
}).collect(Collectors.toList());
ObjectMapper mapper = new ObjectMapper();
mapper.registerModule(new JavaTimeModule());
[{
"processedDate":"2020-01-23",
"FAILED":3,
"ACCEPTED":2
}]