有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java Spring MongoRepository#findall:ConverterNotFoundException

我有两个简单的文档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]

预期产出:

当我调用MyMongoRepo#findByIdentifier(就像在RestController中一样)时,我得到如下结果:

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

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

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


共 (1) 个答案

  1. # 1 楼答案

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

    {
        id: 1,
        nested: "somevalue"
    }
    

    spring无法将String转换为NestedDoc对象

    修复/删除文档,您应该会没事的