Chris L
Chris L

Reputation: 533

Null backreference when mapping to two instances of the same class

I'm currently working with Grails 1.3.7, and I have the following domain classes connected by a pair of one-to-one relationships:

class Parent {

    Child child1
    Child child2

    static constraints = {}
}

and

class Child {

    static belongsTo = [parent:Parent]

    static constraints = {}
}

In a separate service class, I have the following method:

def checkParent(child) {
    log.info(child.parent)
}

Lastly, in my controller, I have the following code:

    Parent parent = new Parent()
    parent.child1 = new Child()
    parent.child2 = new Child()
    parent.save(flush:true)
    childService.checkParent(parent.child1)
    childService.checkParent(parent.child2)

My log output shows me that one of the Child objects always has a null reference to parent, whereas the other has the backreference established as expected.

Why does this happen?

Upvotes: 2

Views: 697

Answers (1)

Mengu
Mengu

Reputation: 524

your Child class should be like this:

class Child {
    Parent parent

    static belongsTo = [Parent]
}

and then your code will work. the other thing is when you have two references to the same domain class for different domain class attributes you may want to check mappedBy.

Upvotes: 1

Related Questions