【问题标题】:Grails hasOne and hasMany with same domain and cascade operationGrails hasOne 和 hasMany 具有相同的域和级联操作
【发布时间】: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


    【解决方案1】:

    根据错误信息(瞬态),你需要saveparent在添加孩子之前:

     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)
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-07-17
      • 2016-02-29
      • 1970-01-01
      • 1970-01-01
      • 2017-05-31
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多