0

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

1 回答 1

2

对于这个用例,您可能真的只想使用标准 GORM 事件,使用isDirty()和getPersistentValue( )至少进行更新。特别是,如 audit-logging 插件的文档中所述,它被设计为在实体被提交到数据存储后对它们工作(因此,例如,保证分配对象 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()))
        }
    }
}

这样一来,在提交更改后修改对象时,您就不会遇到任何麻烦。

于 2011-09-16T22:01:37.043 回答