Java Spring + MongoTemplate无法检索对象列表

时间:2018-07-13 14:30:38

标签: java spring mongodb

我有一个链接到MongoDB集合的Java类:

@Document(collection = "my_collection")
public class Ev extends MyDTO{
    @Id
    private String id;
    @Indexed
    private String sessionId;
    private List<String> findings;
}

我必须在此更改findings

    private List<MyObject> findings;

声明为

public class MyObject {
    private String find;
    private String description;
    private int number;
    private List<SecondaryObj> details;
}

这里是构造函数

public MyObject(String find, int number) {
    super();
    this.find= find;
    this.number= number;
}

public MyObject(String find, int number, List<SecondaryObj> details) {
    super();
    this.find= find;
    this.details = details;
    this.number= number;
}

所以在mongoDB中,我遇到的情况类似于

{
    "_id" : ObjectId("5b487a2667a1aa18f*******"),
    "sessionId" : "abc123mySessionId",
    "findings" : [ 
        {
            "find" : "HTTPS",
            "description" : "I found HTTPS",
            "number" : 10,
            "details": [
                {"a":"1", "b":"2"},
                {"a":"2", "b":"3"}
            ]
        },
        {
            "find" : "NAME",
            "description" : "I found name",
            "number" : 3,
            "details": [
                {"a":"1", "b":"2"},
                {"a":"2", "b":"3"}
            ]
        }
    ]
}

我显然已经更新了所有方法以匹配新数据集,但是如果我尝试检索

Query searchQuery = new Query(Criteria.where("sessionId").is("abc123mySessionId"));
Ev result = mongoTemplate.findOne(searchQuery, Ev.class);

我收到此错误

Request processing failed; nested exception is org.springframework.data.mapping.model.MappingInstantiationException: Failed to instantiate com.my.project.domain.MyObject using constructor NO_CONSTRUCTOR with arguments

有根本原因

java.lang.NoSuchMethodException: om.my.project.domain.MyObject.<init>()

我正在使用spring-data-mongodb version 2.0.8mongo-java-driver version 3.8.0

我认为我应该在某个地方声明MyObject,但是我在Spring还是很新,所以我以一种盲目的方式进行尝试...有什么建议吗?

2 个答案:

答案 0 :(得分:1)

您有两个非零参数的构造函数,而Spring不知道要调用哪个。它尝试调用no-args构造函数,但是您的类没有该构造函数。 检查Spring Data Mongo docs

您可以创建无参数构造函数,并用@PersistenceConstructor批注对其进行标记。通过这种方式,Spring调用它来创建对象,并根据文档字段名称通过反射来设置字段,因此不需要设置器。

答案 1 :(得分:0)

@Document(collection = "my_collection")
public class Ev extends MyDTO{
@Id
private String id;
@Indexed
private String sessionId;
private List<MyObject> findings;}

public class MyObject {
private String find;
private String description;
private int number;}

在此情况下,我在spring-boot-starter-data-mongodb-版本2.0.3.RELEASE中工作正常