Gideon
Gideon

Reputation: 1586

Issue on Grails GORM domain classes with "soft" joins

I have mapped two tables on Domain classes, say:

I want point out that there is no specific foreign keys explicitly declared on the database, rather it is declared on the GORM's mapping. But here's the catch: There are special types of Child that are orphans- that is, doesn't have their Parent table counterparts. Everytime I access these orphans via a valid Child.findById(), an error shows:

Message: No row with the given identifier exists

that is not present when accessing a non-orphan Child. I had marshalled these Domain tables already in such a way that everytime a Child is parsed as JSON, it will have a property called parents which is an array of Parent and the other way around. It is already working- except for these orphans' case.

How should I fixed this? Should I remove their GORM join, since they are not actually joint on the database side?

Upvotes: 0

Views: 57

Answers (1)

Emmanuel Rosa
Emmanuel Rosa

Reputation: 9895

I'm assuming you have domain classes that look like this:

class Parent {
    static hasMany = [children: Child]
}

class Child {
    static belongsTo = [parent: Parent]
}

That's a bi-directional one-to-many association. GORM expects the child table to contain a foreign key to the parent, and the child can only exist if it has a parent.

One way to allow orphan children is do to as you suggested: remove the gorm associations. Another way is to remove the belongsTo to create a uni-directional association. That way a child can exist without a parent.

Upvotes: 1

Related Questions