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

标签 hibernate grails groovy gorm

有什么办法可以使以下结构:

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 ),添加子级之前需要先o​​jit_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/

相关文章:

groovy - 如何在 Groovy 中创建大小为 N 的集合/数组,并将每个单元格初始化为零?

java - Cucumber-JVM Ant 任务

java - Hibernate criteria.setFetchSize 未按预期工作

Spring Boot setResultTransformer 和 addScalar

java - Postgres分区表触发器插入重复记录

grails - 在Grails 3中更改了 View 和模板渲染

jquery - 如何从jquery.html()函数中的属性文件获取值

Grails 无法从表单中级联保存多对一

javascript - 将返回的 Json 响应与发布的响应进行比较

java - Grails 替换一对一关联中的对象