有没有办法制作以下结构:
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,现在多个子实例具有相同的父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与父级。
答案 0 :(得分:1)
根据错误消息(瞬态),您需要在添加子项之前save
parent
:
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)
}