2013-09-16 72 views
0

我試圖實現以下目標:基本上只是應對mongodb文檔並向其中添加時間戳字段,以便重新構建文檔被更改的順序以及萬一需要恢復這些條目。關於使用Salat對版本控制對象的反饋

我的做法是這樣的:

@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的方式來做到這一點?

或者您的方法如何?

由於提前,

斯特凡

回答

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 
    } 

(也DBOS是可變的,所以沒有必要進行呼叫toMap,您可以只直接分配時間戳dbo("timestamp")