我想为嵌套的案例类自动创建 mongo 编解码器,这些案例类很大并且有很多层次的组合。
举个简单的例子,假设我想为以下类创建编解码器:
case class Person(name: String, address: Address, birthDate: Date)
case class Address(country: String, city: String, streetAddress: String)
使用 createCodecProvider 时:
private val customCodecs = Macros.createCodecProvider[Person]()
private val javaCodecs = CodecRegistries.fromCodecs(
new DateCodec())
private val codecRegistry = fromRegistries(fromProviders(customCodecs),
javaCodecs,
DEFAULT_CODEC_REGISTRY)
我收到错误:
org.bson.codecs.configuration.CodecConfigurationException: Can't find a codec for class io.equalum.server.alert.Address.
以下方法确实有效:
private val customCodecs = fromProviders(classOf[Person], classOf[Address])
private val javaCodecs = CodecRegistries.fromCodecs(
new DateCodec())
private val codecRegistry = fromRegistries(customCodecs,
javaCodecs,
DEFAULT_CODEC_REGISTRY)
但是,当然,对于大型案例类,这将很难编写和维护。