java - 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;
}
我怎样才能实现这种行为?
解决方案
推荐阅读
- c# - 如何在uwp中将打印窗口主题灰色更改为黑色?
- java - Spring Boot 使用泛型类型注入 Bean Map
- android - 如何将推送通知从 wordpress 发送到 android 应用程序?
- ios - GMSPlaceRectangularLocationOption iOS swift
- django - 如何在Django中上传多个图像
- python - Python 中的赋值操作是否有布尔值?
- python - 附加熊猫数据框问题
- c# - 统一字符串替换
- windows - PostgreSQL 进程使用大量私有内存
- javascript - 在检索数据时显示加载动画(Angular 10)