How to know if a transactional method in a grails service was successful?

烈酒焚心 提交于 2019-12-02 03:37:26

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:-

  1. 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.

  2. (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....

  3. (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() 

}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!