我试图实现以下目标:基本上只是处理一个mongodb文档,并在其中添加一个时间戳字段,以便重建文档更改的顺序,并在需要时恢复这些条目。
我的做法如下:
@Salat
trait Version[A <: DBEntity] extends ModelCompanion[A, ObjectId] {
def timeStamp: Long = System.currentTimeMillis()
/**
* this method overrides the default salat dao save method in order to make a copy for versioning of Objects
*/
override def save(entity: A) =
{
if (entity.id != null) {
// let salat deserialze the case class into a DBObject
val dbo = dao._grater.asDBObject(entity)
//convert the Object into a Map and append our timestamp
val builder = BasicDBObjectBuilder.start(dbo.toMap()).add("timeStamp", timeStamp)
val copyCollection = MongoDBLayer.mongoDB("history")
//and save it in the historic collection
copyCollection.insert(builder.get())
}
//delegate to the superclass to perform the actual save process
val wr = dao.save(entity)
wr
}
}有没有一种更优雅的/convienent方法来做这件事?
或者你的方法是什么?
提前谢谢你,
斯特凡
发布于 2013-09-17 03:51:37
请参阅SalatDAO#decorateDBO -在每次插入/保存/更新之前调用此方法。这可能是将添加时间戳到DBO并将副本保存在历史集合中的代码的逻辑位置。只需覆盖它并在开始时调用super.decorateDBO。然后继续添加时间戳,并做任何您需要做的事情。
/** A central place to modify DBOs before inserting, saving, or updating.
* @param toPersist object to be serialized
* @return decorated DBO for persisting
*/
def decorateDBO(toPersist: ObjectType) = {
val dbo = _grater.asDBObject(toPersist)
if (forceTypeHints) {
// take advantage of the mutability of DBObject by cramming in a type hint
dbo(ctx.typeHintStrategy.typeHint) = ctx.typeHintStrategy.encode(toPersist.getClass.getName).asInstanceOf[AnyRef]
}
dbo
}(此外,DBO是可变的,因此不需要调用toMap。您可以直接将时间戳分配给dbo("timestamp"))
https://stackoverflow.com/questions/18832993
复制相似问题