gpt4 book ai didi

java - Spring-data-mongo 无法使用构造函数实例化 java.util.List

转载 作者:可可西里 更新时间:2023-11-01 09:11:58 24 4
gpt4 key购买 nike

使用 spring-data-mongodb-1.5.4mongodb-driver-3.4.2

我有一个类旅馆

    public class Hotel {

private String name;
private int pricePerNight;
private Address address;
private List<Review> reviews;
//getter, setter, default constructor, parameterized constructor

复习类:

public class Review {

private int rating;
private String description;
private User user;
private boolean isApproved;
//getter, setter, default constructor, parameterized constructor

当我调用 Aggregation.unwind("reviews"); 它抛出

org.springframework.data.mapping.model.MappingInstantiationException: Failed to instantiate java.util.List using constructor NO_CONSTRUCTOR with arguments

UnwindOperation unwindOperation = Aggregation.unwind("reviews");
Aggregation aggregation = Aggregation.newAggregation(unwindOperation);
AggregationResults<Hotel> results=mongoOperations.aggregate(aggregation,"hotel", Hotel.class);

我看到 this question但对我没有帮助。

如何解决?

最佳答案

当您在 $unwind reviews 字段时,查询的返回 json 结构不再与您的 Hotel 类匹配。因为 $unwindoperation 使 reviews 成为子对象而不是列表。如果你在 robomongo 或其他一些工具中尝试你的查询,你可以看到你的返回对象是这样的

{
"_id" : ObjectId("59b519d72f9e340bcc830cb3"),
"id" : "59b23c39c70ff63135f76b14",
"name" : "Signature",
"reviews" : {
"id" : 1,
"userName" : "Salman",
"rating" : 8,
"approved" : true
}
}

所以你应该使用另一个类而不是 Hotel,比如 UnwindedHotel

public class UnwindedHotel {

private String name;
private int pricePerNight;
private Address address;
private Review reviews;
}

UnwindOperation unwindOperation = Aggregation.unwind("reviews");
Aggregation aggregation = Aggregation.newAggregation(unwindOperation);
AggregationResults<UnwindedHotel> results=mongoOperations.aggregate(aggregation,"hotel", UnwindedHotel.class);

关于java - Spring-data-mongo 无法使用构造函数实例化 java.util.List,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46139856/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com