【发布时间】:2015-11-09 10:27:39
【问题描述】:
我发现了一些与我的问题非常接近的问题(例如Play Framework / Scala: abstract repository and Json de/serialization),但它们并没有解决我的问题。
我想要实现的是对我的 CRUD DAO 的抽象,用于常见的 CRUD 操作。
我为此构建了一个 GenericMongoDaoActor:
abstract class GenericMongoDaoActor[T <: Entity: Writes](implicit inj:Injector, implicit val f:Format[T]) extends Actor with Injectable {
protected val db = inject[DefaultDB]
protected val collectionName: String
protected val collection:JSONCollection
//set to None to use fallback
def defaultSelector(obj:T):Option[JsObject] = None
def fallbackSelector(obj:T) = Json.obj("_id" -> Json.obj("$elemMatch" -> obj._id))
protected def find(jsObject: JsObject) = {
val currentSender = sender
val futureOption = collection
.find(jsObject)
.cursor[T](ReadPreference.primaryPreferred)
.headOption
futureOption.mapTo[Option[T]].flatMap {
case Some(pobj) =>
currentSender ! Some(pobj)
Future{pobj}
case None =>
currentSender ! None
Future{None}
}
}
protected def save(obj:T):Unit = {
update(obj, true)
}
protected def update(obj:T):Unit = {
update(obj, false)
}
private def update(obj:T, upsert: Boolean):Unit = {
val selector = defaultSelector(obj) match {
case None => fallbackSelector(obj)
case Some(sel) => sel
}
collection.update(
selector,
obj,
GetLastError.Default,
upsert).onComplete {
case Failure(e) => Logger.error("[" + this.getClass.getName + "] Couldn`t update " + obj.getClass.getName + ": " + Json.prettyPrint(Json.toJson(obj)), e)
case Success(lastError) => //currentSender ! lastError todo: do something with lastError
}
}
def findAll() = {
collection.find(Json.obj()).cursor[T](ReadPreference.primaryPreferred).collect[List]()
}
}
DAOActor 处理继承抽象类“Entity”的实体:
abstract class Entity {
val _id: BSONObjectID
}
目前有2个类继承Entity..
如您所见,我的 DOAActor 已经绑定在上下文中,可以在范围内查找 Writes[T]..
abstract class GenericMongoDaoActor[T <: Entity: Writes]
当我尝试像这样构建我的项目时,它抱怨在更新方法中没有提供 OWrites 来序列化类型为“T”的“obj”。
No Json serializer as JsObject found for type T. Try to implement an implicit OWrites or OFormat for this type.
collection.update( <-------------
我找不到解决此问题的方法。如果可以,请告诉我。
【问题讨论】:
标签: json scala playframework-2.0 crud reactivemongo