What is the difference between the following actions?
def someAction() {
User.withTransaction { ... }
}
and
def someAction() {
User.withNewTransaction { ... }
}
When do I use what?
When a grails action contains only a Transaction block. In this case I guess withTransaction and withNewTransaction are the same, because each action has its own transaction. Is this true?
I believe these functions have to do with transaction isolation semantics. The withTransaction
function will participate in an existing transaction if one already has been started and would start a new one if not. The withNewTransaction
method will always start a new transaction regardless of if one has already been started, isolating the code inside that block into it's own transaction (with its own commit/rollback).
If you think the method you are developing should or could participate in some larger transaction with multiple separate db writes, then you should use withTransaction
so that you can participate in a larger transaction if necessary. If you want your write here to be totally isolated from other db writes if another transaction is going on (and not potentially roll back that other transaction if this code fails), then use withNewTransaction
.
In regards to your question two, these two will behave the same if they are the only calls being made in an action as they would both start up a new transaction.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With