Grails 1.1 事务编程

Grails是构建在Spring的基础上的,所以使用Spring的事务来抽象处理事务编程,但GORM类通过 withTransaction 方法使得处理更简单,方法的第一个参数是Spring的TransactionStatus 对象.

典型的使用场景如下: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() } } } }在上面的例子中,如果目的账户没有处于活动状态,系统将回滚事务,同时如果有任何异常抛出在事务的处理过程中也将会自动回滚。

假如你不想回滚整个事务,你也可以使用"save points"来回滚一个事务到一个特定的点。

你可以通过使用Spring 的 SavePointManager 接口来达到这个目的。

The withTransaction 方法为你处理begin/commit/rollback代码块作用域内的逻辑。