Play Framework / Scala:抽象存储库和 Json de/serialization

Play Framework / Scala: abstract repository and Json de/serialization

这个问题可能更多地是关于 Scala 而不是 Play,但它是:我正在尝试为常见的数据库操作实现存储库的抽象。

trait Entity {
  def id: UUID
}

trait Repository[T <: Entity] {

  val JSON_KEY_ID = "_id"

  def collection: JSONCollection

  def insert(t: T): Future[Either[String, T]] = {
    collection.insert(t).map(wr => if (wr.ok) Right(t) else Left(wr.getMessage()))
      .recover { case t => Left(t.getMessage) }
  }

   def update(t: T): Future[Either[String, T]] = {
    val selector = Json.obj(JSON_KEY_ID -> t.id.toString)
    collection.update(selector, t).map(wr => if (wr.ok) Right(t) else Left(wr.getMessage()))
      .recover { case t => Left(t.getMessage) }
  }
}

然后我有了我想使用的对象:

case class UserDAO(id: UUID) extends Entity[UserDAO]

object UserDAO {
  val JSON_KEY_ID = "_id"

  implicit val userDaoWrites: OWrites[UserDAO] = new OWrites[UserDAO] {
    def writes(user: UserDAO): JsObject = Json.obj(
      JSON_KEY_ID -> JsString(user.id.toString)
    )
  }

  implicit val userDaoReads: Reads[UserDAO] = (
    (__ \ JSON_KEY_ID).read[UUID]
    )(UserDAO.apply _)
}

然后我这样定义它的存储库:

class UserRepository @Inject()(val reactiveMongoApi: ReactiveMongoApi) extends Repository[UserDAO] {
  val db = reactiveMongoApi.db
  override def collection: JSONCollection = db.collection[JSONCollection]("users")
}

我得到的错误是

No Json serializer as JsObject found for type T. Try to implement an implicit OWrites or OFormat for this type.
collection.insert(t).map(wr => if (wr.ok) Right(t) else Left(wr.getMessage()))
                 ^

我试过提供implicit OWrites[T],甚至implicit OWrites[_]都无济于事。也许我想要实现的目标是不可能的。如果没有,我该如何解决?非常感谢。

您应该可以只使用上下文绑定。

trait Entity {
  def id: UUID
}

class Repository[T <: Entity : Writes] {
  ...
}

这将确保如果范围内存在隐式 Writes[T],它将可用于您的插入和更新功能。