Spring-data-mongo无法使用Constructor实例化java.util.List

Meh*_*lik 4 java spring mongodb spring-data spring-data-mongodb

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

我上了课 Hotel

    public class Hotel {

        private String name;
        private int pricePerNight;
        private Address address;
        private List<Review> reviews;
//getter, setter, default constructor, parameterized constructor 
Run Code Online (Sandbox Code Playgroud)

Review 课程:

public class Review {

    private int rating;
    private String description;
    private User user;
    private boolean isApproved;
 //getter, setter, default constructor, parameterized constructor 
Run Code Online (Sandbox Code Playgroud)

当我打电话时Aggregation.unwind("reviews");它会抛出

org.springframework.data.mapping.model.MappingInstantiationException:无法使用带参数的构造函数NO_CONSTRUCTOR实例化java.util.List

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

我看到这个问题,但对我没有帮助.

怎么解决这个?

bar*_*ini 5

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

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

所以你应该使用另一个类而不是HotelUnwindedHotel

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);
Run Code Online (Sandbox Code Playgroud)

  • @MehrajMalik乐意提供帮助.以及我为查询做的一般建议.首先将它们构建为本机mongodb查询,然后通过robomongo等直接尝试.然后将其编码为spring-data.因此,您可以确定您的查询是否有效并按预期返回值. (2认同)