2011-09-16 5 views
0

grails audit logging plugin을 성공적으로 작동 시켰습니다. onChange 메소드 내에서 감사 대상 도메인 객체에 대한 참조를 얻는 방법을 알 수 없다는 점을 제외하고는 꼭 필요한 것처럼 보입니다. 아래는 플러그인의 예를 들어 Person 클래스의 코드 내가 달성하기 위해 노력하고있어 몇 가지 추가 라인이다 :이 사용 사례를 들어Grails Audit Loggin plugin의 onChange 메소드에서 소유하고있는 감사 대상 도메인 객체에 대한 참조를 얻으려면 어떻게해야합니까?

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

답변

2

, 당신은 아마 정말 isDirty()getPersistentValue()를 사용하여 the standard GORM events를 사용하려면 최소한 업데이트를하기 위해서. 특히 as noted in the documentation for the audit-logging plugin은 데이터 저장소에 커밋 된 후에 엔터티에서 작업하도록 설계되었습니다 (예를 들어, 개체 ID가 할당되도록 보장). 당신은 그것의 변경이 커밋 된 후 객체를 변경하는 어떤 funkiness에 충돌하지 않아야

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

그 방법 :

은 다음과 같은 것을보십시오.

+0

내 목표를 달성하는 데 훨씬 깨끗한 방법입니다. – esdot