title: grails withTransaction - why is it on a domain object?
body: <p>We need to be able to rollback a complex transaction in a service, without throwing an exception to the caller.  My understanding is that the only way to achieve this is to use withTransaction.</p>
  
  <p>The question is:</p>
  
  <ol>
  <li>why do I have to call this on a domain object, such as Books.withTransaction </li>
  <li>What if there is no relevant domain object, what is the consequence of picking a random one?</li>
  </ol>
  
  <p>Below is more or less what I am trying to do.  The use case is for withdrawing from an account and putting it onto a credit card.  If the transfer fails, we want to rollback the transaction, but not the payment record log, which must be committed in a separate transaction (using RequiresNew).  In any case, the service method must return a complex object, not an exception.</p>
  
  <p>someService.groovy</p>
  
  <pre><code>Class SomeService {
      @NotTransactional
      SomeComplexObject someMethod() {
          SomeDomainObject.withTransaction{ status -&gt;
              DomainObject ob1 = new DomainObject.save()
              LogDomainObject ob2 = insertAndCommitLogInNewTransaction()
              SomeComplexObject ob3 = someAction()
              if (!ob3.worked) {
                   status.setRollbackOnly() // only rollback ob1, not ob2!
              }
              return ob3
          }
      }
  }
  </code></pre>
  
  <p>The above is flawed - I assume "return ob3" wont return ob3 from the method, as its in a closure. Not sure how to communicate from inside a closure to outside it.</p>