我正在努力实现以下目标:基本上只需处理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
}
}
有没有更优雅/更方便的方式呢?
或者你的方法会怎样?
提前致谢,
的Stefan
答案 0 :(得分:0)
请参阅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")
)