1

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

Denny
  • 449
  • 4
  • 17
  • why would you need it? do you need to duplicate the objects in session or in the db? – injecteer Sep 25 '14 at 09:51
  • 1
    This answer might help you: [proper-implementation-of-clone-for-domain-classes-to-duplicate-a-grails-domain](http://stackoverflow.com/questions/20220711/proper-implementation-of-clone-for-domain-classes-to-duplicate-a-grails-domain) – PhilMr Sep 25 '14 at 10:27
  • AFAIK there is nothing. The oldschool approach is to navigate your hierarchy, `setId(null)` and hope for the best. You may have a chance to a generic solution in your case using gorm meta informations. – cfrick Sep 25 '14 at 10:28
  • @PhilMr clone copy only object itself ? , I need to create all child object too – Denny Sep 29 '14 at 09:40

1 Answers1

1

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.

Community
  • 1
  • 1
Steinar
  • 5,860
  • 1
  • 25
  • 23