映射到同一个类的两个实例时为空反向引用

时间:2011-12-08 23:04:42

标签: grails orm gorm

我目前正在使用Grails 1.3.7,并且我通过一对一对一的关系连接了以下域类:

class Parent {

    Child child1
    Child child2

    static constraints = {}
}

class Child {

    static belongsTo = [parent:Parent]

    static constraints = {}
}

在单独的服务类中,我有以下方法:

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

最后,在我的控制器中,我有以下代码:

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

我的日志输出显示Child个对象之一总是parent有空引用,而另一个对象的反向引用按预期建立。

为什么会这样?

1 个答案:

答案 0 :(得分:1)

你的Child课程应该是这样的:

class Child {
    Parent parent

    static belongsTo = [Parent]
}

然后你的代码就可以了。另一件事是,对于不同的域类属性,您有两个对同一域类的引用,您可能需要检查mappedBy

相关问题