Overriding default Transactional Behaviour in Grails Services using Annotations

28 / Apr / 2010 by Vivek Krishna 1 comments

In a project, we needed to have fine tune the transaction behaviour on our Service classes. One service method was calling the a method in another service. The calling service method A was to happen in one transaction and the called service method B in its own transaction. This was required because we needed to persist the error log from the B() in a domain using A().

Even though an exception was thrown from B() and it was caught in A() and handled gracefully, some exceptions were thrown, which meant that the changes made in A() were also rolled back, which was not the behavior we required. After some investigation and taking cue from the mailing list , it was decided that the best way to go about it was to run B() in its own transaction. This was possible using the Spring Transaction Annotation, a property of which creates a new session for B().

This was done by adding the annotation

   import org.springframework.transaction.annotation.*
   class SampleService{
        static transactional = true
        @Transactional(propagation = Propagation.REQUIRES_NEW)
         def B(){
                   //..implementation which can throw exceptions. The logic in this method is run in a single transaction

And in A(), we have try catch blocks to handle the exception.

Hope this helps.


comments (1 “Overriding default Transactional Behaviour in Grails Services using Annotations”)

Leave a Reply

Your email address will not be published. Required fields are marked *