2

I have the following action:

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
  }
}

When running, I sometimes get the following error:

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]

Why does this error happen? I thought withNewTransaction would prevent this error.

4444
  • 3,541
  • 10
  • 32
  • 43
  • 1
    You might want to look at http://stackoverflow.com/questions/8645694/row-was-updated-or-deleted-by-another-transaction-or-unsaved-value-mapping-was – 4444 Aug 07 '13 at 18:19
  • I am new in Grails can you exmplain this answer? –  Aug 07 '13 at 18:24

1 Answers1

7

You can use pessimistic locking

Use:

User user = User.lock(params.userId)

or

User user = User.findById(params.userId, [lock: true])    
Michael
  • 32,527
  • 49
  • 210
  • 370