【问题标题】:Best Way to Create MongoDB Projections with Nested Objects in Spring Boot Data在 Spring Boot Data 中使用嵌套对象创建 MongoDB 投影的最佳方法
【发布时间】:2022-09-27 22:44:18
【问题描述】:

我正在获取现有的 MongoDB 集合并将其包装在 Spring Boot 应用程序的存储库中。文档可能非常大,因此在很多情况下我们只想拉回其中包含的字段的子集。当我尝试做一个涉及嵌套对象的投影时,我得到一个MappingInstantiationException

我有一个这样的对象结构:

@Document
data class OuterDocument(
    @Id
    val id: String,
    val bar: String,
    val nested: NestedDocument
)

data class NestedDocument(
    val nestedFoo: String
)

// This is the class I want to project into
data class OuterDto(
    val id: String,
    val nested: NestedDocument
)

我的存储库如下所示:

interface OuterRepository: MongoRepository<OuterDocument, String> {
    @Query(\"{id:  ?0}\")
    fun getDto(id: String): OuterDto?
}

调用它时,我得到这个异常:

org.springframework.data.mapping.model.MappingInstantiationException: Failed to instantiate org.springframework.data.mapping.model.MappingInstantiationException: Failed to instantiate OuterDto using constructor fun <init>(kotlin.String, NestedDocument): OuterDto with arguments null,null
    at app//org.springframework.data.mapping.model.ClassGeneratingEntityInstantiator$EntityInstantiatorAdapter.createInstance(ClassGeneratingEntityInstantiator.java:290)
    at app//org.springframework.data.mapping.model.ClassGeneratingEntityInstantiator.createInstance(ClassGeneratingEntityInstantiator.java:102)
    at app//org.springframework.data.mongodb.core.convert.MappingMongoConverter.doReadProjection(MappingMongoConverter.java:374)
...

我不确定这种方法是否适用应该工作,但是通过代码跟踪,它似乎真的很努力地去做,而且它在没有嵌套对象的情况下工作(例如,如果我在 DTO 中将 nested 替换为 bar,就可以了)。

这似乎类似于this question,但我没有嵌套我的类型声明,这似乎是那里的根本问题。

getDto 显示的表格应该有效吗?我需要对我的类或函数进行一些修改吗?

    标签: spring kotlin spring-data-mongodb


    【解决方案1】:

    使用投影进行显式管道似乎适用于所有场景(嵌套对象与否):

    @Aggregation(pipeline = [
        "{ \$match: { id: ?0 } }",
        "{ \$project: { id: 1, nested: 1 } }",
    ])
    fun getDto(id: String): OuterDto?
    

    这是一个合理的后备。唯一的缺点是,在实践中,投影需要更多的字段,并且需要与 DTO 保持同步;如果框架只能推断出要投影的字段(就像没有嵌套对象时那样),那就太好了。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-02-05
      • 2012-09-25
      • 2020-07-01
      • 2018-08-07
      • 2020-06-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多