Search code examples
grailsinsertself-reference

Grails self referencing domain class surprising save result


I have a self-referencing domain class like this:

class Person {
   String name
   Person father
   Person mother
}

I have no hasMany or other constraints on father or mother

I have a service that inserts new entries from a .csv file as follows

Person father = Person.findBy(newPersonFatherName)
Person mother = Person.findBy(newPersonMotherName)
Person newPerson = new Person(
    name: newPersonName,
    father: father,
    mother: mother)
newPerson.save()

What happens when this is executed is the maternal grandmother and paternal grandfather are both set to the same instance as newPerson.

I can make this go away by inserting the following two lines before the save()

Person pgf = father.father
Person pgm = father.mother
Person mgf = mother.father
Person mgm = mother.mother

I guess the whole thing is somehow related to cascading saves but I'm unable to really understand the problem, and I'm reluctant to leave such a poorly understood solution in place in the code.

Can anyone help? Thanks in advance!


Solution

  • It seems this problem has gone away somewhere between Grails 2.5.5 and Grails 3.3 so I'm going to mark this as answered and solved.