首页 > 解决方案 > GORM:继承字段的更改不是 isDirty()?

问题描述

修改继承的多对一关系字段后,无法使用isDirty()或类似的检查来检测更改。如何在不手动检查字段的情况下检测更改?

我已经尝试使用@DirtyCheck,但这仅适用于简单字段,例如lookupId. @DirtyCheck不修复关系字段,例如lookup.

利用:

以下测试正在通过并显示当前的不良行为。

@Unroll
def 'MyObject dirty check with setter: #setter'() {
    given: '2 existing Lookups and a newly created MyObject'
        Lookup lookup1 = new Lookup(
            code: 'CODE1'
        ).save(flush: true, failOnError: true)
        Lookup lookup2 = new Lookup(
            code: 'CODE2'
        ).save(flush: true, failOnError: true)
        MyObject myObject = new MyObject(
            name: 'someName',
            lookup: Lookup.get('CODE1'),
        ).save(flush: true, failOnError: true)
    when: 'change the lookup'
        if(setter) {
            myObject.setLookup(Lookup.get('CODE2'))
        } else {
            myObject.lookup = Lookup.get('CODE2')
        }
    then: 'we can manually detect the change'
        myObject.lookup.code == 'CODE2'
        myObject.getPersistentValue('lookup').code == 'CODE1'
        myObject.getPersistentValue('lookup') != myObject.lookup
        myObject.getPersistentValue('lookup').code != myObject.lookup.code
    and: 'dirty checks do not detect the change'
        false == (myObject.lookup.getDirtyPropertyNames() ||
            myObject.getDirtyPropertyNames() ||
            myObject.lookup.isDirty() ||
            myObject.lookup.hasChanged() ||
            myObject.hasChanged() ||
            myObject.isDirty() ||
            ((LookupBase)myObject.lookup).isDirty() ||
            ((LookupBase)myObject.lookup).hasChanged() ||
            ((ModelBase)myObject).isDirty() ||
            ((ModelBase)myObject).hasChanged()
        )
    where:
        setter << [false, true]
}

有一个父类:

@ToString(includeNames=true)
@EqualsAndHashCode(
    includes = [ 'lookup', 'lookupId', ]
)
@AutoClone
class ModelBase {
    UUID id

    Lookup lookup
    String lookupId
}

还有另一个父类:

@ToString(includeNames=true)
@EqualsAndHashCode(
    includes = [ 'code', ]
)
class LookupBase {
    String code

    static constraints = {
        code nullable: false
    }

    static mapping = {
        id name: 'code', generator: 'assigned'
    }
}

一个子类:

@Entity
@ToString(
    includeNames=true,
    includeSuperProperties=true,
    excludes = [ ... ]
)
@EqualsAndHashCode(
    callSuper = true,
    excludes = [ ... ]
)
class MyObject extends ModelBase implements GormEntity<MyObject> {
    String name
}

还有另一个子类:

@Entity
@ToString(includeNames=true, includeSuperProperties=true)
@AutoClone
class Lookup extends LookupBase implements GormEntity<Lookup> {
    static constraints = {
        code maxSize: 20
    }
}

标签: grailsgroovygrails-orm

解决方案


在不深入研究代码的情况下,您是否尝试过添加@DirtyCheck到父类、子类或两个类定义中?src/main/groovy当从非 Domain ( ) 类继承的 Domain 类必须显式添加到父类中时,我看到了类似的行为。

编辑:对不起,没有看到你说你已经尝试过的帖子的结尾。


推荐阅读