In the Grails Audit Loggin plugin's onChange method, how do I get a reference to the owning auditable domain object?
I've successfully gotten the grails audit logging plugin to work, looks like exactly what I need except I can't figure out how to get a reference to the auditable domain object from within the onChange method. Below is the code from the plugin's example Person class, with a few additional lines of what I'm trying to achieve:
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 开发者_如何学C" + 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()
)
}
}
})
}
}
For this use-case, you probably really just want to use the standard GORM events using isDirty() and getPersistentValue() at least to make the updates. In particular, as noted in the documentation for the audit-logging plugin, it is designed to work on entities after they have been committed to the data store (and so, for example, the object id is guaranteed to be assigned).
Try something like the following:
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()))
}
}
}
That way you shouldn't hit into any funkiness with modifying the object after it's changes have been committed.
精彩评论