首页 > 解决方案 > MongoDbConverters 用于多态类型的混合集合

问题描述

我有一个 mongo 集合,其中包含所有相同基本类型的元素。有的有_class属性,有的没有。我已经为基本元素注册了一个 mongo 转换器,并且看到它在缺少 _class 属性时会被适当地触发。对于确实存在的元素,Spring 尝试为该子类型元素查找转换器,但随后失败。我已经尝试为子类型对象创建一个转换器,但我希望它只利用可能发生的“默认”行为。

@JsonTypeInfo(
    use = JsonTypeInfo.Id.NAME,
    include = JsonTypeInfo.As.EXISTING_PROPERTY,
    property = "type",
    visible = true
)
abstract class ElementBase {}

class myElement: ElementBase{}

我的转换器适用于没有_class属性的元素

class ElementConverter : Converter<Document, ElementBase> {
   override fun convert(source: Document): ElementBase? {
      // maps to object that inherits from element base
      val mapper: ObjectMapper = SerializationUtils.buildJacksonObjectMapper()
      return mapper.convertValue(source, myElement::class.java)
   }
}

子类型对象的转换器:

abstract class SurveyElementConverterBase(val applicationContext: ApplicationContext) {
    inline fun <reified T: SurveyElement> defaultConvert(source: Document): T {
        // One approach, but requires that I add the type attribute to the 
        // document even if I'm explicitly trying to create a sub type. 
        // Also has problems if there are nested elements, as those elements 
        // also require the type attribute.
        val mapper: ObjectMapper = SerializationUtils.buildJacksonObjectMapper()
        return mapper.convertValue(source, T::class.java)

        // Results in a stack overflow
        val mongoTemplate: MongoTemplate = applicationContext.getBean(MongoTemplate::class.java)
        return mongoTemplate.converter.read(T::class.java, source)
    }
}

当存在 _class 属性时,我可以使用默认的转换器行为吗?或者我如何设置转换器,以便它在知道子类型时认为不需要使用自定义转换器?

Spring Boot 2.4 Kotlin 1.4.32 Spring Data Mongo 3.1

标签: spring-bootspring-dataspring-data-mongodb

解决方案


推荐阅读