有什么办法可以使以下结构:
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。
最佳答案
根据错误消息( transient ),添加子级之前需要先ojit_code save
:
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)
}
关于hibernate - Grails的hasOne和hasMany具有相同的域和级联操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38665175/