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?

Answers


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()
}

Need Your Help

Debug WCF service called by a windows service in C#

c# wcf

I have a Windows service that has been scheduled using Quartz.NET. I have to debug it. As I cannot debug the start method, I put a breakpoint on the Execute method. I compiled my solution and insta...

What's wrong with my Checklist code?

java android android-fragments checklist

I am trying to implement @federicoiosue (Github) CheckListView into my app. I am having problems figuring out why it's not working correctly.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.