问题描述
我需要一次保存多个对象,并且如果一个对象无法保存则全部回滚。
例如:
class Transaction {
Item item;
}
class物品{
date lastTransaction;
$ b如果我创建新的事务,我需要更改lastTransaction值并保存项目。
如果我没有保存该项目,我需要回滚交易(反之亦然)。
有什么想法吗? p>
解决方案 Yuck。不要抛出异常来回滚事务。如果事务管理器假设运行时异常意味着您不在控制之下,并且自动执行滚动操作,那么使用 副作用 支持你的交易以防止你受到更多的伤害。这有点像寂寞,用锤子反复敲打头部,所以一些EMT,也许护士或医生会花一些时间陪你。
这很漂亮很容易回滚一个事务,但不幸的是Grails并没有公开这些内容:
import org.springframework.transaction.interceptor .TransactionAspectSupport
$ b class FooService {
def someMethod(...){
boolean somethingBadHappened = ...
if(somethingBadHappened ){
//回滚
TransactionAspectSupport.currentTransactionStatus()。setRollbackOnly()
}
//继续
...
$ / code>
稍后您可以检查当前事务是否回滚
TransactionAspectSupport.currentTransactionStatus()。isRollbackOnly()
请注意,这不适用于一个控制者,因为交易将以该点结束。
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;
}
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).
Any ideas?
解决方案 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.
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 - 保存多个对象,如果保存失败,则回滚所有对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!