GORM能否复制整个对象? [英] can GORM duplicate whole object?
问题描述
我们使用grails开发一些web应用程序
对于具有子类的Domain类,我想知道是否可以复制包含属于Parent的所有子对象的整个对象?
谢谢
如评论中所述,您可以使用 clone
方法。 然而,如果你不想混淆gorm api,一个非常简单的解决方案就是分离现有的对象,然后保存它。请注意,这不会执行 deepClone
。
步骤:
- 清空ID。
- 更新副本中不同的字段。
- 分离对象
代码示例,假设一个域类
Region
,它有一个唯一的名称
属性,需要在保存前更改:
< pre $def copyRegion(Region region,String newName){
region.id = null
region.name = newName
region.discard()
if(region.save()){
//句柄成功
} else {
//句柄错误
}
}
另见。
we are using grails to develop some web application For Domain class that have child class , I'm wondering if we can duplicate whole object including all child object that belong to Parent ?
Thank you
解决方案As given in the comments, you can extend gorm with a
clone
method.However, a very simple solution if you don't want to mess with the gorm api is to detach the existing object and just "resave" it. Note that this won't perform a
deepClone
.Steps:
- Null the id.
- Update fields that should differ in the copy.
- Detach the object in question.
- Save it.
Code example, assuming a domain class
Region
which has a uniquename
property that needs to change before saving:def copyRegion(Region region, String newName) { region.id = null region.name = newName region.discard() if (region.save()) { // handle success } else { // handle error } }
See also this question about disconnecting an object.
这篇关于GORM能否复制整个对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!