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.
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 setfailOnError
flag too. Alternative approach is to setgrails.gorm.failOnError=true
inConfig.groovy
which automatically checks for each save and throws aValidationException
in case validation on domain class fails.ValidationException
is aRuntimeException
therefore transaction will be rolled back if one thrown. Have a look at failOnError to get the idea.(Little less verbose in your case) Save method returns the domain object itself in case of a success otherwise null if validation fails. Again you have trace all the
saves
to check something likeif(a.save()){...}
,if(b.save()){...}
, blah, blah....(I think the appropriate approach) Will be to use
TransactionAspectSupport
to get the transaction status and check if it is set to rollback only. 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()
}
来源:https://stackoverflow.com/questions/17357145/how-to-know-if-a-transactional-method-in-a-grails-service-was-successful