Grails:仅在全部通过验证时将 parent 和 children 保存到数据库的方法

Grails: way to save a parent and children to database ONLY if all pass validation

我有一个 parent object 只有 children 有效才能创建。 . Children 只能在保存后通过 id 引用 parent(因为 id 是自动递增的)。所以我保存了parent,然后将parent分配给children保存。 如果一个 child 保存失败,我如何回滚所有 parent 保存和任何已发生的 child 保存?

(发生在服务层)

 parent.save(flush:true);
 children.each{child->
     child.parent=parent;
     if(!child.save(flush:true)){
            //how to roll back all previous child saves if any AND 
            //initial parent save also
     }
 }

如果您在事务服务中抛出未捕获的异常,事务将回滚所有内容。像这样:

package com.example

class MyService {

    static transactional = true

    void myMethod() {
      parent.save(flush:true)
      children.each{child->
        child.parent = parent
        if(!child.save(flush:true)){
          throw new RuntimeException('Rollback')
       }
     }
    }
}

就我个人而言,我不会在生产代码中使用 RuntimeException。在这种情况下,我会创建自己的异常并避免填写堆栈跟踪。但是,出于示例目的,上面演示了您想要做什么。