[英]How to know if a transactional method in a grails service was successful?
I have something like this: 我有这样的事情:
class SomeService {
static transactional = true
def someMethod(){
...
a.save()
....
b.save()
....
c.save()
....
etc...
}
} }
I want to know if the transactional method was successful or not, I don't want to check the error property in each domain object because the logic involve many domain classes and it would be difficult. 我想知道事务方法是否成功,我不想检查每个域对象中的error属性,因为逻辑涉及许多域类,而且这很困难。
Use 采用
a.save(failOnError: true)
b.save(failOnError: true)
c.save(failOnError: true)
d.save(failOnError: true)
I'm assuming what you want is the service to throw exception on error of a single domain save, and rollback the transaction in such cases. 我假设您想要的服务是在单个域保存错误时引发异常,并在这种情况下回滚事务。
There are number of ways you can check the same:- 您可以通过多种方式进行检查:-
As you do not want to trace all the saves
in the service class, I guess you would also not like tracing each of the save to set failOnError
flag too. 由于您不想跟踪服务类中的所有saves
,因此我想您也不想跟踪每个保存都设置failOnError
标志的情况。 Alternative approach is to set grails.gorm.failOnError=true
in Config.groovy
which automatically checks for each save and throws a ValidationException
in case validation on domain class fails. 另一种方法是在Config.groovy
设置grails.gorm.failOnError=true
,如果对域类的验证失败,它将自动检查每个保存并抛出ValidationException
。 ValidationException
is a RuntimeException
therefore transaction will be rolled back if one thrown. ValidationException
是一个RuntimeException
因此如果抛出一个事务,该事务将被回滚。 Have a look at failOnError to get the idea. 看一下failOnError可以得到这个主意。
(Little less verbose in your case) Save method returns the domain object itself in case of a success otherwise null if validation fails. (在您的情况下,稍为冗长)Save方法在成功的情况下返回域对象本身,在验证失败时返回null。 Again you have trace all the saves
to check something like if(a.save()){...}
, if(b.save()){...}
, blah, blah.... 再次,您将跟踪所有saves
以检查类似if(a.save()){...}
, if(b.save()){...}
,等等等等。
(I think the appropriate approach) Will be to use TransactionAspectSupport
to get the transaction status and check if it is set to rollback only. (我认为适当的方法)将使用TransactionAspectSupport
来获取事务状态并检查它是否设置为仅回滚。 If it is not then you are good. 如果不是,那你就很好。
For example: 例如:
def someMethod(){
try{
...
a.save()
....
b.save()
....
c.save()
....
etc...
}catch(e){
//It can also be used as a last line in method instead of checking
//in catch block.
println TransactionAspectSupport.currentTransactionStatus().isRollbackOnly()
}
//println TransactionAspectSupport.currentTransactionStatus().isRollbackOnly()
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.