# Grails 1.1 事务编程

**URL:** <https://www.isharkfly.com/t/grails-1-1/6646>\
**Category:** 程序语言\
**Created:** [November 4, 2012, 4:30pm UTC](https://www.isharkfly.com/t/grails-1-1/6646 "2012-11-04T16:30:18Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![honeymoose](https://www.isharkfly.com/user_avatar/www.isharkfly.com/honeymoose/32/20796_2.png) [@honeymoose](https://www.isharkfly.com/u/honeymoose)\
**Post date:** [November 4, 2012, 4:30pm UTC](https://www.isharkfly.com/t/grails-1-1/6646/1 "2012-11-04T16:30:18Z")

</div>

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代码块作用域内的逻辑。
