2

我有以下动作:

def index() {

  User.withNewTransaction {

   def user = User.get(params.userId)
   user.name = "test"
   user.save(flush:true)

   response.setContentType("image/gif")
   response.outputStream << PIXEL_BYTES_OF_A_GIF_IMAGE
   return
  }
}

运行时,有时会出现以下错误:

Message
Executing action [index] of controller [test.TestController] caused exception: Runtime error executing action
Caused by
Row was updated or deleted by another transaction (or unsaved-value mapping was incorrect): [test.User#1]

为什么会发生此错误?我认为withNewTransaction可以防止这个错误。

4

1 回答 1

7

您可以使用悲观锁定

采用:

User user = User.lock(params.userId)

或者

User user = User.findById(params.userId, [lock: true])    
于 2013-08-07T22:04:10.357 回答