0

Exception I get when saving child record before the parent one:

GrailsWrappedRuntimeException: ORA-02291:
integrity constraint (GRB.FKF8F6B734389E9766) violated -
parent key not found

The code:

class Child {
    Parent parent
    static constraints = {
        parent nullable: true
    }
}

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

def child = new Child()
child.save() // first save of Child

def parent = new Parent()
parent.save()

//session.flush() // the sudden flush

child.parent = parent
child.save()

// here is 'constraint violation' when transaction is committed

As it is said in the exception message, Child has parent key Parent set, but somehow the key is not seen as an existing row by Hibernate at that moment...

Above is a simplified reconstruction of events happening in my code. Please note these actions are performed in different places of code (designed to be separated from each other). Unfortunately such a minified code works well and does not reproduce the problem... Also I never met such problem before - I used to save child records before parent ones and vice versa without any problem.

I could fix the code in two ways:

  • commenting "first save" of Child (ordering of saves is important?!)
  • or uncommenting the session flush

Although I could fix it I really don't want depend on such things like order of save's or sudden flush'es... Any idea how to cure the problem still having reliable code?

Grails 2.2.0, Hibernate 3.6, Oracle XE

4

1 回答 1

0

您的例外可能是因为您在子表上没有可空parent约束的情况下进行了测试。如果没有可为空的,现有条目和新条目中将有 0 或其他内容,因为 DB 正在做一些魔术。GORM 不会删除现有的 FK,也不会向现有列添加可为空的约束。尝试手动删除约束或删除整个列。仔细检查parent_id列上的可为空约束。

关于您的问题,我会建议您将孩子添加到父母身上,而不是将孩子保存为孩子:

parent.addToChildren(child)

如果之前没有保存过,这也隐含地保存了孩子。

于 2013-08-10T16:30:34.727 回答