微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

使用spring-data-mongodb-1.5.4和mongodb-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(“评论”);它抛出

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 review字段中,查询的返回json结构不再与您的Hotelclass匹配.因为$unwindoperation使评论成为子对象而不是列表.如果您在robomongo或其他工具中尝试查询,则可以看到您的返回对象就是这样

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

所以你应该使用另一个班而不是Hotellike 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);

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐