Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between withTransaction and withNewTransaction?

What is the difference between the following actions?

def someAction() {
  User.withTransaction { ... } 
}

and

def someAction() {
  User.withNewTransaction { ... }
}
  1. When do I use what?

  2. 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?

like image 686
confile Avatar asked Aug 01 '13 12:08

confile


1 Answers

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.

like image 195
cmbaxter Avatar answered Oct 23 '22 12:10

cmbaxter