2013-09-16 2 views
0

Я пытаюсь добиться следующего: в основном просто копируя документ mongodb и добавляю к нему поле метки времени, чтобы восстановить порядок, в котором документ был изменен, и в случае необходимости восстановить эти записи.Обратная связь по объектам Versioning с 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"))