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 set failOnError
flag too. 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. ValidationException
is a RuntimeException
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 like if(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()
}