////
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements.  See the NOTICE file
distributed with this work for additional information
regarding copyright ownership.  The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License.  You may obtain a copy of the License at

https://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied.  See the License for the
specific language governing permissions and limitations
under the License.
////


== withTransaction



=== Purpose


Allows programmatic transactions using Spring's Transaction abstraction.


=== Examples


[source,groovy]
----
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()
        }
    }
}
----

Named arguments may optionally be passed as an argument to control attributes of the transaction.

[source,groovy]
----
// 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]) {
    // ...
}
----


=== Description


The `withTransaction` method accepts a Closure with a {springapi}org/springframework/transaction/TransactionStatus.html[TransactionStatus] argument. The `TransactionStatus` object can be used to programmatically control rollback of the transaction.

Refer to the user guide section of  link:{hibernate5GuideFromRef}index.html#programmaticTransactions[Programmatic Transactions] for more information.
