【问题标题】:How to deep clone domain object in grails 3.3.11?如何在 grails 3.3.11 中深度克隆域对象?
【发布时间】:2020-04-21 06:57:25
【问题描述】:

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

我试过下面的sn-p:

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 版本中工作。

【问题讨论】:

    标签: grails clone grails-domain-class grails-3.3.x


    【解决方案1】:

    我参考文档Upgrading from Grails 3.2.x解决了这个问题

    这里是新代码sn-p:

    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 包。

    【讨论】:

      猜你喜欢
      • 2010-09-09
      • 1970-01-01
      • 2019-08-09
      • 1970-01-01
      • 2012-06-05
      • 2013-09-06
      • 2010-10-15
      相关资源
      最近更新 更多