What is the difference between withTransaction and withNewTransaction?

亡梦爱人 提交于 2020-01-24 04:02:06

问题


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?


回答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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!