RRK
RRK

Reputation: 465

Grails Domain - Child with multiple parent cascade behavior

I have the following domain classes

class Child {
    static belongsTo = [parent1: Parent1, parent2: Parent2] 
    static constraints = {
        parent1(nullable: true)
        parent2(nullable: true)
    }
}

class Parent1 {
    Child singleChild
}

class Parent2 {
    static hasMany = [children: Child]
    static mappedBy = [children: 'parent2']
    static mapping = {
        children cascade: "all, all-delete-orphan"
    }
}   

Child belongs to Parent1 and/or Parent2.

Parent1 has oneToOne relation with Child and Parent2 has oneToMany relation with Child.

Problem: If I delete Parent1, I see that Child that belongs to BOTH Parent1 and Parent2 gets deleted.

Question: Is there a way to NOT automatically delete a Child if it ALSO belongs to Parent2?

Upvotes: 1

Views: 736

Answers (1)

RRK
RRK

Reputation: 465

I was able to overcome this issue by doing the following:

For cascade save and update

1) Remove [parent1: Parent] from belongsTo in the Child class

2) Add cascade: "save-update" to Parent1 class.

This is the modified Child and Parent class. No change to Parent2

class Child {
    static belongsTo = [parent2: Parent2] 
    static constraints = {
        parent2(nullable: true)
    }
}

class Parent1 {
    Child singleChild
    static mapping = {
        singleChild cascade: "save-update"
    }
}

When Parent1 is deleted, I check if singleChild has Parent2. If not, then i delete singleChild. Here is the code

if(parent1.singleChild.parent2 ==  null) {
    parent1.singleChild.delete()
}

Upvotes: 1

Related Questions