简体   繁体   English

特质和继承类的Mongodb Scala驱动程序编解码器

[英]Mongodb scala driver codec for trait and inherited classes

Using the following mongo-driver . 使用以下mongo-driver I want to insert and get structures (see below) from MongoDB. 我想从MongoDB中插入并获取结构(见下文)。

 trait A {
   def id: ObjectId
 }

 case class B(id: ObjectId) extends A

 case class C(id: ObjectId, name: String) extends A

I find a solution with using sealed classes, but I want to use traits. 我找到了使用密封类的解决方案,但我想使用特征。 I want to find a solution with Codecs or something else. 我想找到使用编解码器或其他解决方案。

I had the same concern just a few days ago but didn't find anything in the documentation regarding sealed traits for modeling ADT in MongoDB. 几天前,我也有同样的担忧,但是在文档中没有找到有关在MongoDB中对ADT建模的sealed traits任何信息。

In the end, I used sealed class as suggested in the official scala driver github repo . 最后,按照官方scala驱动程序github repo的建议,我使用了sealed class

If you really want to use traits (due to the definition of abstract methods) you can do something like this: 如果您真的想使用特征(由于定义了抽象方法),则可以执行以下操作:

package example.model

import example.model.adt._
import org.mongodb.scala.bson.ObjectId
import org.mongodb.scala.bson.codecs.Macros._
import org.mongodb.scala.bson.codecs.DEFAULT_CODEC_REGISTRY
import org.bson.codecs.configuration.CodecRegistries.{fromProviders, fromRegistries}

trait MongoModel {
  def _id: ObjectId
}

object MongoModel {
  val codecRegistery = fromRegisteries(fromProviders(classOf[A]), DEFAULT_CODEC_REGISTRY)
}

Now you can have your ADT for A defined with sealed class . 现在,您可以使用sealed class定义A的ADT。

package example.model.adt

import example.model.MongoModel
import org.mongodb.scala.bson.ObjectId

sealed class A

final case class B(_id: ObjectId) extends A with MongoModel
final case class C(_id: ObjectId) extends A with MongoModel

This answer doesn't solve the question directly but provides a feasible workaround. 该答案不能直接解决问题,而是提供了可行的解决方法。 Note that this code is just an example. 请注意,此代码仅是示例。 For a more complete implementation, you can see this github repo . 有关更完整的实现,请参见此github repo

Since release 2.7, the mongodriver is now able to serialize sealed traits . 从2.7版本开始,mongodriver现在可以序列化 sealed traits
It works exactly like serializing a sealed classes. 它的工作原理与序列化密封类完全相同。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM