GORM能否复制整个对象? [英] can GORM duplicate whole object?

查看:112
本文介绍了GORM能否复制整个对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们使用grails开发一些web应用程序
对于具有子类的Domain类,我想知道是否可以复制包含属于Parent的所有子对象的整个对象?



谢谢

解决方案

如评论中所述,您可以使用 clone 方法。 然而,如果你不想混淆gorm api,一个非常简单的解决方案就是分离现有的对象,然后保存它。请注意,这不会执行 deepClone



步骤:


  1. 清空ID。

  2. 更新副本中不同的字段。
  3. 分离对象




  4. 代码示例,假设一个域类 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:

    1. Null the id.
    2. Update fields that should differ in the copy.
    3. Detach the object in question.
    4. Save it.

    Code example, assuming a domain class Region which has a unique name 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆