我正在尝试 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 中工作版本。

请您参考如下方法:

我引用文档 Upgrading from 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 
    } 

根据文档:

The GrailsDomainClassProperty interface had many more methods to evaluate the type of the property such as isOneToOne, isOneToMany etc. and while PersistentProperty does not provide direct equivalents you can use instanceof as a replacement using one of the subclasses found in the org.grails.datastore.mapping.model.types package.


评论关闭
IT序号网

微信公众号号:IT虾米 (左侧二维码扫一扫)欢迎添加!