Search code examples
grailsgrails-ormaop

How to detect which field has been updated in afterUpdate|beforeUpdate GORM methods


i use afterUpdate method reflected by GORM API in grails project.

class Transaction{

    Person receiver;
    Person sender;


}

i want to know which field modified to make afterUpdate behaves accordingly :

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();
      }

   }
}

I can use beforeUpdate: and catch up the object before updating in global variable (previous as Transaction), then in afterUpdate, compare previous with the current object. Could be?


Solution

  • Typically this would be done by using the isDirty method on your domain instance. For example:

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

    However, in your case if you are using afterUpdate() the value has already been persisted to the database and isDirty won't ever return true.

    You will have to implement your own checks using beforeUpdate. This could be setting a transient value that you later read. For example:

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