How to know if a transactional method in a grails

2019-02-28 03:01发布

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.

2条回答
该账号已被封号
2楼-- · 2019-02-28 03:08

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.

查看更多
成全新的幸福
3楼-- · 2019-02-28 03:31

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

}
查看更多
登录 后发表回答