[英]Grails: way to save a parent and children to database ONLY if all pass validation
I have a parent object that can only be created if children are valid. 我有一个父对象,仅当子对象有效时才能创建。 .
。 Children can only reference parent by id after it has been saved (since id is auto incremented).
子代只能在保存后按ID引用父对象(因为ID是自动递增的)。 SO I save the parent and then assign the parent to the children to save.
因此,我保存了父级,然后将父级分配给要保存的子级。 How do I rollback all the parent save and any child saves that have occurred if one child fails to be saved?
如果一个孩子未能保存,我该如何回滚所有父保存和所有子保存?
(This is taking place in a service layer) (这是在服务层中进行的)
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
}
}
If you throw an uncaught exception in a transactional service the transaction will rollback everything. 如果在事务服务中引发未捕获的异常,则事务将回滚所有内容。 Something like this:
像这样:
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')
}
}
}
}
Personally I wouldn't use a RuntimeException
in production code. 就个人而言,我不会在生产代码中使用
RuntimeException
。 I'd create my own exception and avoid filling in the stacktrace in this case. 在这种情况下,我将创建自己的异常并避免填写stacktrace。 However, for example purposes the above demonstrates what you would want to do.
但是,出于示例目的,以上内容演示了您想要执行的操作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.