问题
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?
回答1:
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 it's 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.
来源:https://stackoverflow.com/questions/17994372/what-is-the-difference-between-withtransaction-and-withnewtransaction