首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用Salat对对象进行版本控制的反馈

使用Salat对对象进行版本控制的反馈
EN

Stack Overflow用户
提问于 2013-09-16 16:32:03
回答 1查看 124关注 0票数 0

我试图实现以下目标:基本上只是处理一个mongodb文档,并在其中添加一个时间戳字段,以便重建文档更改的顺序,并在需要时恢复这些条目。

我的做法如下:

代码语言:javascript
复制
@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方法来做这件事?

或者你的方法是什么?

提前谢谢你,

斯特凡

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2013-09-17 03:51:37

请参阅SalatDAO#decorateDBO -在每次插入/保存/更新之前调用此方法。这可能是将添加时间戳到DBO并将副本保存在历史集合中的代码的逻辑位置。只需覆盖它并在开始时调用super.decorateDBO。然后继续添加时间戳,并做任何您需要做的事情。

代码语言:javascript
复制
   /** 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"))

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/18832993

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档