grails - 在Grails审核日志记录插件的onChange方法中,如何获得对拥有的可审核域对象的引用?

标签 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()
                 )
              }
           } 
        }) 
     }
   }

最佳答案

对于此用例,您可能真的只想至少使用the standard GORM eventsisDirty()来使用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()))
        }
    }
}

这样一来,您就不必在更改对象后修改对象,而使它变得时髦。

关于grails - 在Grails审核日志记录插件的onChange方法中,如何获得对拥有的可审核域对象的引用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7449134/

相关文章:

grails - 将 namespace 放在url中

android - 从代码更改插件操作图标

javascript - 在 jQuery 周历插件中将非工作时间变灰

java - Spock - 提取与方法的交互

mysql - 字段 'class' 没有默认值

Grails 错误代码

grails - 将图像与Grails Assets 管道捆绑在一起是否有意义?

java - 如何分发多模块maven项目

java - JAVA中的static Initializer是闭包吗

sql - 为什么这个 Groovy MetaClass 语句可以与 Sql 类一起使用?