gpt4 book ai didi

grails - 如何在 grails 3.3.11 中深度克隆域对象?

转载 作者:行者123 更新时间:2023-12-02 14:39:02 24 4
gpt4 key购买 nike

我正在尝试 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.

关于grails - 如何在 grails 3.3.11 中深度克隆域对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61337636/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com