Grails 从父域模型更新一对多

标签 grails

我正在从 Controller 中的父域模型更新一对多。

代码如下所示:

def update() {

   def parentInstance = Parent.get(params.id)

   params.childerenDetails.each {

      parentInstance.addToChildrens(
         newChildren(
            name:params.get(name_"${it}"),
            age:params.get(age_"${it}"))
      }
   }

   if(parentInstance.validate()) {
      parentInstance.save(flush:true)
   } else {
      render "error found at"+parentInstance.errors
   }
}

....这里我在父类中有自定义验证,当添加子值得到父验证错误但子对象正在保存到数据库中..如果验证错误出现在父域中,如何防止

最佳答案

如果您想防止将 child 存储到数据库中,您需要将此代码移动到 Service ,默认是事务性的,或者将所有代码封装在 Parent.withTransaction { // } 中.如果您选择使用该服务,您可以发送 RuntimeException当您检测到验证错误以强制回滚时。如果您使用 withTransaction ,您可以使用 status.setRollbackOnly 手动回滚:

def parentInstance = Parent.get(params.id)
Parent.withTransaction { status ->
   params.childerenDetails.each {

     parentInstance.addToChildrens(
        newChildren(
           name:params.get(name_"${it}"),
           age:params.get(age_"${it}"))
       }
   }

   if(parentInstance.validate()) {
      parentInstance.save(flush:true)
   } else {
     status.setRollbackOnly()
   }
}

不确定 parentInstance.save(flush: true, failOnError: true)也会触发回滚。
我更愿意将业务逻辑移至服务。见 withTransactionServices引用指南中的文档。

关于Grails 从父域模型更新一对多,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27457042/

相关文章:

java - Grails 1.2.0 - 强制服务回滚

grails - 在Grails中将Cookie httpOnly设置为false。

grails - Groovy 的 Duck 接口(interface)?

grails - 在 Grails/Groovy 中加载插件管理器时出错

java - 使用工作流引擎、状态机引擎还是自己动手?

unit-testing - Grails-表ID默认为不能为null还是可以?

Grails 3 - 获取服务中的 Assets 路径

image - 如何在Grails GSP中显示图像?

hibernate - Grails 2.5至Grails 3.2 GORM 6

选择 jquery,空字符串作为选项