【发布时间】:2016-07-29 18:17:13
【问题描述】:
有没有什么方法可以制作以下结构:
class Parent {
String name
static hasOne = [firstChild: Child]
static hasMany = [otherChildren: Child]
}
class Child{
String name
static belongsTo = [parent: Parent]
}
现在当我尝试运行一个简单的代码时:
Parent p = new Parent(name: "parent", firstChild: new Child(name: 'child'))
p.addToOtherChildren(new Child(name: "child2"));
p.addToOtherChildren(new Child(name: "child3"));
p.save(flush: true)
它保存了对象,但是当我尝试对 Parent 进行列表操作时,它会抛出此错误:
org.springframework.orm.hibernate4.HibernateSystemException: More than one row with the given identifier was found: 2, for class: test.Child; nested exception is org.hibernate.HibernateException: More than one row with the given identifier was found: 2, for class: test.Child
这里的问题是 hasOne 将 Parent id 存储在 Child 中,hasMany 和 belongsTo 一样,现在多个子实例具有相同的 parent id,因此很难确定哪个是 firstChild。
我也试过this solution,但它抛出了这个异常:
org.springframework.dao.InvalidDataAccessApiUsageException: Not-null property references a transient value - transient instance must be saved before current operation : test.Child.parent -> test.Parent; nested exception is org.hibernate.TransientPropertyValueException: Not-null property references a transient value - transient instance must be saved before current operation : test.Child.parent -> test.Parent
有没有更好的方法或者我做错了什么?
我想级联保存 firstChild 和 otherChild 与父母。
【问题讨论】:
标签: hibernate grails groovy grails-orm