【问题标题】:How to detect which field has been updated in afterUpdate|beforeUpdate GORM methods如何在 afterUpdate|beforeUpdate GORM 方法中检测哪个字段已更新
【发布时间】:2014-09-16 13:47:08
【问题描述】:

我在 grails 项目中使用 GORM API 反映的 afterUpdate 方法。

class Transaction{

    Person receiver;
    Person sender;


}

我想知道修改哪个字段以使 afterUpdate 有相应的行为:

class Transaction{
     //...............
   def afterUpdate(){
      if(/*Receiver is changed*/){
        new TransactionHistory(proKey:'receiver',propName:this.receiver).save();
      }
      else
      {
      new TransactionHistory(proKey:'sender',propName:this.sender).save();
      }

   }
}

我可以使用beforeUpdate: 并在更新之前在全局变量(之前为Transaction)中赶上对象,然后在afterUpdate 中,将previous 与当前对象进行比较。 可以吗?

【问题讨论】:

    标签: grails grails-orm aop


    【解决方案1】:

    通常这将通过在您的域实例上使用isDirty 方法来完成。例如:

    // returns true if the instance value of firstName 
    // does not match the persisted value int he database.
    person.isDirty('firstName')
    

    但是,在您的情况下,如果您使用的是 afterUpdate(),则该值已经保存到数据库中,isDirty 永远不会返回 true。

    您必须使用beforeUpdate 实施您自己的检查。这可能是设置您稍后读取的瞬态值。例如:

    class Person {
      String firstName
      boolean firstNameChanged = false
      static transients = ['firstNameChanged']
      ..
      def beforeUpdate() {
        firstNameChanged = this.isDirty('firstName')
      }
      ..
      def afterUpdate() {
        if (firstNameChanged)
        ...
      }
    ...
    }
    

    【讨论】:

    • 谢谢你。但这意味着对于每个字段,我们有 2 个字段(Changed)
    • 或者你使用beforeUpdate()。正如我所指出的,如果您使用的是afterUpdate(),那么使用瞬变跟踪更改是唯一的其他解决方案
    • 看起来 wasDirty 会派上用场
    猜你喜欢
    • 1970-01-01
    • 2014-08-03
    • 2016-03-05
    • 1970-01-01
    • 2020-02-06
    • 2011-08-21
    • 2018-03-02
    • 1970-01-01
    • 2012-01-11
    相关资源
    最近更新 更多