(快速參考)

withTransaction

目的

允許使用 Spring 的交易抽象來編寫程式交易。

範例

Account.withTransaction { status ->

    def source = Account.get(params.from)
    def dest = Account.get(params.to)

    int amount = params.amount.toInteger()
    if (source.active) {
        source.balance -= amount

        if (dest.active) {
            dest.amount += amount
        }
        else {
            status.setRollbackOnly()
        }
    }
}

命名參數可以選擇性地作為參數傳遞,以控制交易的屬性。

// the keys in the Map must correspond to properties
// of org.springframework.transaction.support.DefaultTransactionDefinition

Account.withTransaction([propagationBehavior: TransactionDefinition.PROPAGATION_REQUIRES_NEW,
                         isolationLevel: TransactionDefinition.ISOLATION_REPEATABLE_READ]) {
    // ...
}

說明

withTransaction 方法接受一個 Closure,其參數為 TransactionStatusTransactionStatus 物件可用於以程式方式控制交易的回滾。

請參閱使用者指南的 程式交易 部分,以取得更多資訊。