在Grails Audit Loggin插件的onChange方法中,如何获取对拥有可审计域对象的引用?



我已经成功地得到了grails审计日志插件的工作,看起来就像我所需要的,除了我不能弄清楚如何从onChange方法中获得对可审计域对象的引用。下面是插件的示例Person类的代码,还有我想要实现的一些额外的行:

class Person {
   static auditable = true 
   Long id 
   Long version
   String firstName 
   String middleName 
   String lastName
   String email
   static hasMany = [emailRecords : EmailRecord]    
   static constraints = { 
      firstName(nullable:true,size:0..60) 
      middleName(nullable:true,size:0..60) 
      lastName(nullable:false,size:1..60) 
      email(email:true) 
   }
   def onSave = { 
      println "new person inserted" // may optionally refer to newState map 
   } 
   def onDelete = { 
      println "person was deleted" // may optionally refer to oldState map 
   } 
   def onChange = { 
     oldMap,newMap -> 
        println "Person was changed ..." 
        oldMap.each({ key, oldVal -> 
           if(oldVal != newMap[key]) { 
              println " * $key changed from $oldVal to " + newMap[key] 
              // how can achieve something like this?
              if(key == "email"){
                 def personInstance = this // this didn't work, I'm not sure how I can get such a reference to the owning domain object
                 personInstance.addToEmailRecords(
                    new EmailRecord(
                       email:newMap[key],
                       date: new Date()
                    ).save()
                 )
              }
           } 
        }) 
     }
   }

对于这个用例,您可能真的只想使用标准的GORM事件,至少使用isDirty()和getPersistentValue()来进行更新。特别是,正如审计日志插件的文档中所指出的,它被设计为在实体被提交到数据存储后工作(因此,例如,对象id被保证分配)。

尝试如下内容:

class Person {
    // blah, blah, blah
    def beforeInsert = {
        if (email) {
            addToEmailRecords(new EmailRecord(email: email, date: new Date()))
        }
    }
    def beforeUpdate = {
        if (isDirty("email")) {
            addToEmailRecords(new EmailRecord(email: email, date: new Date()))
        }
    }
}

最新更新