问题描述
我需要一次保存多个对象,如果一个对象保存失败,则全部回滚.例如:
I need to save multiple object at once, and rollback all if one object fails to save.For example :
class Transaction {
Item item;
}
class Item {
date lastTransaction;
}
如果我创建新事务,我需要更改 lastTransaction 值并保存该项目.
如果我保存项目失败,我需要回滚事务(反之亦然).
If I create new Transaction, I need to change lastTransaction value and save the item.
If I failed to save the item, I need to rollback the Transaction (vice versa).
有什么想法吗?
推荐答案
糟糕.不要抛出异常来回滚事务.利用副作用,您将承担相当高的成本,其中事务管理器假设运行时异常意味着您无法控制,会自动滚动为您支持交易,以防止您造成更大的损失.这有点像孤独并用锤子反复敲击自己的头部,所以一些 EMT 和护士或医生可能会花一些时间陪你.
Yuck. Don't throw exceptions to roll back transactions. You're incurring a pretty high cost to take advantage of a side effect where the transaction manager, assuming that a runtime exception means that you're not in control, automatically rolls back the transaction for you to keep you from doing more damage. It's a bit like being lonely and hitting yourself in the head repeatedly with a hammer so some EMTs and perhaps a nurse or a doctor will spend some time with you.
回滚事务很容易,但不幸的是 Grails 没有公开任何这些:
It's pretty easy to roll back a transaction, but unfortunately Grails doesn't expose any of this:
import org.springframework.transaction.interceptor.TransactionAspectSupport
class FooService {
def someMethod(...) {
boolean somethingBadHappened = ...
if (somethingBadHappened) {
// roll back
TransactionAspectSupport.currentTransactionStatus().setRollbackOnly()
}
// ok, proceed
...
}
}
然后您可以检查当前事务是否已回滚
And later you can check if the current transaction was rolled back with
TransactionAspectSupport.currentTransactionStatus().isRollbackOnly()
请注意,这在控制器中不起作用,因为到那时事务将结束.
Note that this won't work in a controller since the transaction will have ended by that point.
这篇关于Grails - 保存多个对象,如果保存失败则回滚所有对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!