无法获取grails中关联字段的dirtyPropertyNames属性值

时间:2015-10-29 11:15:59

标签: mongodb grails

我需要检查对象的先前状态,以便记录发生的更改。我正在使用dirtyPropertyNames来提取这些属性, 但它没有给我持久的关联字段值,我的代码在下面给出

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的持久值:

def beforeUpdate(){
    this.dirtyPropertyNames?.collect { name ->
        def originalValue = this.getPersistentValue(name)
        def newValue = this."$name"
        println "$name : old:: $originalValue , new:: $newValue ."
    }
}

但是员工记录中的技能和地址的持久值根本没有显示,我正在使用MongoDB。

1 个答案:

答案 0 :(得分:1)

目前,MongoDB的GORM未在dirtyPropertyNames字段中提供正确的值。因此,您必须在域实例中使用另一个较低级别的注入字段,即$changedProperties

但是,$changedProperties也存在问题,即使您绑定具有相同值的字段,$changedProperties也会有一个条目。因此,您可以稍微调整它以使代码工作:

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"
                        }
                    }
                }
            }
        }
    }
}