## 5.6 Programmatic Transactions

Grails is built on Spring and hence uses Spring's Transaction abstraction for dealing with programmatic transactions. However, GORM classes have been enhanced to make this more trivial through the withTransaction method which accepts a block the first argument to which is the Spring TransactionStatus object.

A typical usage scenario is as follows:

    def transferFunds = {
    	Account.withTransaction { status ->
    		def source = Account.get(params.from)
    		def dest = Account.get(params.to)		def amount = params.amount.toInteger()
    		if(source.active) {
    			source.balance -= amount
    			if(dest.active) {
    				dest.amount += amount
    			}
    			else {
    				status.setRollbackOnly()
    			}
    		}
    	}}

In this example we rollback the transactions if the destination account is not active and if any exception are thrown during the process the transaction will automatically be rolled back.

You can also use "save points" to rollback a transaction to a particular point in time if you don't want to rollback the entire transaction. This can be achieved through the use of Spring's SavePointManager interface.

The withTransaction method deals with the begin/commit/rollback logic for you within the scope of the block.