2017-09-10 27 views
0

实例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 

Review类:

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

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

我看到this question但简化版,帮助我。

如何解决这个问题?

+1

9/10时候你真的只需要一个普通的BSON对象,比如'Document.class'或'DBObject.class'来作为聚合输出。聚合通过定义它们的意图来改变输出形状。通常你不需要严格的输出类型,除非你真的需要**一些自定义的序列化。对于其他一切,只需使用泛型。这就是他们在那里。 –

回答

1

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

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

所以,你应该使用另一个类,而不是像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); 
+0

你又救了我:) –

+1

@MehrajMalik乐意帮忙。以及我为我的查询所做的一般性建议。首先将它们构建为本地mongodb查询,然后通过robomongo等直接尝试,然后将其编码为spring-data。因此,您可以确保您的查询能够正常工作并按预期返回值。 – barbakini

+0

感谢您的黄金提示。 –