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

时间:2011-09-16 18:51:55

标签: grails plugins groovy onchange audit-logging

我已经成功地使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()
                 )
              }
           } 
        }) 
     }
   }

1 个答案:

答案 0 :(得分:2)

对于此用例,您可能真的只想使用the standard GORM events isDirty()getPersistentValue()来进行更新。特别是as noted in the documentation for the audit-logging plugin,它被设计为在实体提交到数据存储之后处理它们(例如,保证分配对象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()))
        }
    }
}

这样,在提交更改后,您不应该修改对象。