Spring MongoRepository#findall:ConverterNotFoundException

时间:2017-09-13 11:37:51

标签: java spring mongodb spring-data spring-mongodb

我有两个简单的文档MyDocNestedDoc

MyDoc

public class MyDoc {

    @Id
    private final String id;
    private final NestedDoc nested;


    public MyDoc (MyIdentifier myIdentifier, Nested nested) {

        this(myIdentifier.toString(), 
                new NestedDoc(nested.getIdentifier(), nested.getStp()));

    }

    @PersistenceConstructor
    public MyDoc (String id, NestedDoc nestedDoc) {
        this.id = id;
        this.nestedDoc = nestedDoc;
    }

    // ...

}

NestedDoc

public class NestedDoc {

    private final String identifier;
    private final Stp stp; // is an enum    

    @PersistenceConstructor
    public NestedDocDoc (String identifier, Stp stp) {
        this.identifier = identifier;
        this.stp = type;
    }

    // ...

}

有一个直接的存储库:

public interface MyMongoRepo extends MongoRepository<MyDoc, String> {
    default MyDoc findByIdentifier (MyIdentifier identifier) {
        return findOne(identifier.toString());
    }
}

现在,当我致电MyMongoRepo#findAll时,我得到了

org.springframework.core.convert.ConverterNotFoundException: 
No converter found capable of converting from type [java.lang.String] 
to type [com.xmpl.NestedDoc]

预期的Outpout:

当我调用MyMongoRepo#findByIdentifier时(就像在RestController中一样),我会得到类似的内容:

{
    id: 123,
    nested: {
        identifier: "abc",
        stp: "SOME_CONSTANT",
    }
}

MyMongoRepo#findAll应该返回一个包含所有已知MyDoc的数组。

除了问题之外,了解为什么首先需要转换器会很有趣。在需要转换字符串的引擎盖下会发生什么?

1 个答案:

答案 0 :(得分:1)

您的数据库中有mongo文档,如下所示

{
    id: 1,
    nested: "somevalue"
}

并且spring无法将String转换为NestedDoc对象。

修复/删除文档,你应该没事。