我已经成功使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 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()))
}
}
}
这样一来,您就不必在更改对象后修改对象,而使它变得时髦。
关于grails - 在Grails审核日志记录插件的onChange方法中,如何获得对拥有的可审核域对象的引用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7449134/