Grails hasOne 和 hasMany 具有相同的域和级联操作

Grails hasOne and hasMany with same domain and cascade operation

有什么方法可以制作以下结构:

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 和 otherChildren 与父级。

根据错误消息(瞬态),您需要 save parent 添加 children 之前:

 Parent p = new Parent(name: "parent")

 if(p.save()){
     p.firstChild=new Child(name: 'child');
     p.addToOtherChildren(new Child(name: "child2"));
     p.addToOtherChildren(new Child(name: "child3"));
     p.save(flush: true)
}