无法获取grails中关联字段的dirtyPropertyNames属性值 [英] Unable to get dirtyPropertyNames properties values for association fields in grails
问题描述
我需要检查对象的前一个状态,以便记录发生的更改。我使用 dirtyPropertyNames
来提取这些属性,
,但它没有给出关联字段的持久值,我的代码如下所示
I need to check the previous state of the object so to log the changes happened. I'm using dirtyPropertyNames
to extract such properties,
but it is not giving me the persisted values of association fields, my code is given below
class Employee {
String name
String title
String city
List<Address> addresses
List<Skill> skills
static hasMany = [skills:Skill,addresses:Address]
}
static belongsTo = [Skill]
static embedded = ['skills', 'addresses']
}
在 beforeUpdate()
方法,当我检查 dirtyProperties
时,它给了我持久值 name,title,city
使用下面的代码:
In my code in beforeUpdate()
method, when I check the dirtyProperties
it gives me the persistent values of name, title, city
using the code below :
def beforeUpdate(){
this.dirtyPropertyNames?.collect { name ->
def originalValue = this.getPersistentValue(name)
def newValue = this."$name"
println "$name : old:: $originalValue , new:: $newValue ."
}
}
但员工记录中持续存在的技能和地址值根本没有显示,我使用的是MongoDB。
but the persisted values of skills and address in employee record are not shown at all, I'm using MongoDB.
推荐答案
目前,MongoDB的GORM并没有在 dirtyPropertyNames
字段。因此,您必须在域实例中使用另一个较低级别的注入字段,即 $ changedProperties
。
Currently, GORM for MongoDB does not give correct values in the dirtyPropertyNames
field. So you have to use another lower level injected field in the domain instance i.e. $changedProperties
.
但是,对于 $ changedProperties
也是一个问题,即使您将一个字段绑定为相同的值, $ changedProperties
也会有一个条目。所以你可以稍微调整一下,以使代码正常工作:
But, there is also a problem with the $changedProperties
that even if the you bind a field with the same value, the $changedProperties
will have an entry for it. So you can tweak it a little more like this to make your code work:
def beforeUpdate() {
def instance = this
Map updatedFields = instance.$changedProperties
updatedFields.each { name, value ->
if (updatedFields[name] != instance[name]) {
println "Field value $name is updated"
if (name == "addresses") {
// I've not run this for a long time, just confirm the old and new addresses values and swap the assignment of below lines
List newAddresses = updatedFields[name]
List oldAddresses = instance[name]
newAddresses.each { address ->
if (!address.id) {
println "Got new address: $address.status"
} else {
Address oldAddress = oldAddresses.find { it.id == address.id }
if (!oldAddress) { // This is just an edge condition
println "Got new address: $address.status"
} else if (oldAddress.status != address.staus) {
println "$address status is updated to $address.status"
}
}
}
}
}
}
}
这篇关于无法获取grails中关联字段的dirtyPropertyNames属性值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!