错误:行已被另一个事务更新或删除(或未保存的值映射不正确)

时间:2013-08-07 18:16:18

标签: spring hibernate grails transactions grails-2.0

我有以下行动:

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会阻止此错误。

1 个答案:

答案 0 :(得分:6)

您可以使用pessimistic locking

使用:

User user = User.lock(params.userId)

User user = User.findById(params.userId, [lock: true])