Spring-data-mongo 无法使用构造函数实例化 java.util.List [英] Spring-data-mongo unable to instantiate java.util.List using Constructor

查看:366
本文介绍了Spring-data-mongo 无法使用构造函数实例化 java.util.List的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 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 

复习类:

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:无法使用构造函数 NO_CONSTRUCTOR 实例化 java.util.List带参数

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);

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

I see this question but does't help me.

如何解决这个问题?

推荐答案

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

When you $unwind reviews field, query's return json structure does not match with your Hotelclass anymore. Because $unwindoperation makes reviews a sub object instead of a list. If you try your query in robomongo or some other tools, you can see your return object is like that

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

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

So you should use another class instead of 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);

这篇关于Spring-data-mongo 无法使用构造函数实例化 java.util.List的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆