首页 > 解决方案 > Spring MongoDB - 使用抽象/密封类字段

问题描述

sealed class Entity

data class Bacteria(
    val uid: String,
    val rank: String,
    val division: String,
    val scientificname: String,
    val commonname: String
): Entity()

data class CTDDisease(
    val diseaseId: String,
    val name: String,
    val altDiseaseIds: List<String>,
    val parentIds: List<String>,
    val definition: String?
) : Entity()

然后我想将我的文档定义为

@Document(collection = "annotations")
data class Annotation(
    @Id val id: String,
    ...
    val spans: List<AnnotationSpan>
)

data class AnnotationSpan(
    val startIndex: Int, 
    val endIndex: Int, 
    val entity: Entity? // Can be Bacteria or Disease or null
)

RequestBody我也时不时地从客户那里接受这两个课程,例如

@PutMapping("/annotations")
fun submitAnnotations(@RequestBody submission: Submissions): Mono<Void> { ... }

data class Submission(val annotations: List<AnnotationSpan>, ...) // AnnotationSpan contains Entity

但我明白了

java.lang.IllegalAccessException: class kotlin.reflect.jvm.internal.calls.CallerImpl$Constructor cannot access a member of class com.package.name.Entity with modifiers "private"

如果我将类更改Entity为抽象类

abstract class Entity

然后我没有收到错误,但我的查询操作会一直持续下去。

Bacteria并且Disease两者都有不同的字段,因此它们应该是可区分的。

我尝试使用 hacky 转换器

@ReadingConverter
class NormalizedEntityReaderConverter: Converter<DBObject, NormalizedEntity> {
    override fun convert(source: DBObject): NormalizedEntity? {
        println(source.toString())
        val gson = Gson()
        return gson.runCatching { fromJson(source.toString(), CTDDisease::class.java) }.getOrNull()
                ?: gson.runCatching { fromJson(source.toString(), Bacteria::class.java) }.getOrNull()
    }

}

然后像这样注册它

@Configuration
class MongoConverterConfig {

    @Bean
    fun customConversions(): MongoCustomConversions {
        val normalizedEntityReaderConverter = NormalizedEntityReaderConverter()
        val converterList = listOf<Converter<*, *>>(normalizedEntityReaderConverter)
        return MongoCustomConversions(converterList)
    }
}

我的转换器在手动调用时似乎可以工作,但由于某种原因,Spring 仍然没有接受它。

我是春天的新手。我将通过在 TypeScript 中使用联合类型在我的 Node.js 服务器中实现此功能,例如

interface AnnotationSpan {
    startIndex: number;
    endIndex: number;
    entity?: Bacteria | Disease;
}

我怎样才能实现这种行为?

标签: javaspring-bootkotlinspring-mongodb

解决方案


推荐阅读