1

我正在尝试deep clone我的域对象。它有大约 10 个一对一的映射,而且还有更多。

我尝试了以下代码段:

def deepClone() {
        def copy = this.class.newInstance()

        PersistentEntity entity = Holders.grailsApplication.mappingContext.getPersistentEntity(this.class.name)
        entity?.persistentProperties?.each { prop ->
            if (prop.isAssociation()) {
                if (prop.isOneToOne()) {
                    copy."${prop.name}" = this."${prop.name}"?.deepClone()
                } else if (prop.isOneToMany()) {
                    this."${prop.name}".each {
                        copy."addTo${StringUtils.capitalize(prop.name)}"(it?.deepClone())
                    }
                }
            } else if (prop.name != 'id') {
                if (this."${prop.name}" instanceof List) {
                    this."${prop.name}".each {
                        copy."addTo${StringUtils.capitalize(prop.name)}"(it)
                    }
                } else {
                    copy."${prop.name}" = this."${prop.name}"
                }
            }
        }

        return copy
    }

但是prop.isAssociation没有找到。有谁知道如何检查关联grails 3.3.11。这曾经在1.3.7版本中工作。

4

1 回答 1

2

我参考从 Grails 3.2.x 升级的文档解决了这个问题

这是新的代码片段:

def deepClone() {

        def copy = this.class.newInstance()
        Holders.grailsApplication.mappingContext.getPersistentEntity(this.class.name)?.persistentProperties?.each { prop ->
            if (prop instanceof Association) {
                if (prop instanceof OneToOne) {
                    copy."${prop.name}" = this."${prop.name}"?.deepClone()
                } else if (prop instanceof OneToMany) {
                    this."${prop.name}".each {
                        copy."addTo${StringUtils.capitalize(prop.name)}"(it?.deepClone())
                    }
                }
            } else if (prop.name != 'id') {
                if (this."${prop.name}" instanceof List) {
                    this."${prop.name}".each {
                        copy."addTo${StringUtils.capitalize(prop.name)}"(it)
                    }
                } else {
                    copy."${prop.name}" = this."${prop.name}"
                }
            }
        }
        return copy
    }

根据文档:

GrailsDomainClassProperty 接口有更多方法来评估属性的类型,例如 isOneToOne、isOneToMany 等,虽然 PersistentProperty 不提供直接等效项,但您可以使用 instanceof 作为替代,使用 org.grails.datastore 中的子类之一。 mapping.model.types 包。

于 2020-04-21T09:53:47.890 回答