Thursday 9 October 2008

Programmatic Transactions

By default grails starts a new transaction the first time it enters a service method and commits the transaction when it returns. You can disable this behaviour by declaring your service to be non transactional.

Sometimes you need more fine grained control. Here's a link to a great discussion which unfortunately doesn't seem to have made it into the Grails manual yet, however this is still talking about declarative transactions, rather than programmatic ones.

If you really do want programmatic transactions you can use
DomainObj.withTransactions { TransactionStatus ts ->
serviceA.doStuff()
serviceA.doMoreStuff()
serviceB.yawn()
}

But the caveat (and reason for this post) is that in the above scenario will only create a new transaction if one does not already exist. If the above is placed in a controller it will work fine. If it's placed in a service with
static boolean transactional = false

it will work fine, PROVIDING that the service is being called by a controller or other non-transactional service, however if your non-transactional service is called by a transactional one, the withTransactions block will have no effect.

No comments: