0

I've seen that others have had this problem, but I have yet to find a solution that works in my case. In my update method of my domain controller, I am trying to implement optimistic locking by checking version and using rejectValue(); however, I am clearly doing something wrong. I have verified that rejectValue() is being called, but it doesn't appear to work.

Also, the domain instance with bad data saves anyway. Any advice or help is appreciated. Here is my update method with the problem:

def update(Cohort cohortInstance) {
    if (cohortInstance == null) {
        notFound()
        return
    }

    cohortInstance = Cohort.get(params.id)
    if (cohortInstance == null) {
        notFound()
        return
    }

   if (params.version) {
        def version = params.version.toLong()
        if (cohortInstance.version > version) {
            cohortInstance.errors.rejectValue("version", "default.optimistic.locking.failure",
                      [message(code: 'cohort.label', default: 'Cohort')] as Object[],
                      "Another user has updated this Cohort while you were editing")
            render(view: "edit", model: [cohortInstance: cohortInstance])
            return
        }
    }

    // Bind browser data to this cohort Instance now that we've passed the concurrency check
    cohortInstance.properties = params

    if (cohortInstance.hasErrors()) {
        respond cohortInstance.errors, view:'edit'
        return
    }

    cohortInstance.save flush:true

    request.withFormat {
        form multipartForm {
            flash.message = message(code: 'default.updated.message', args: [message(code: 'Cohort.label', default: 'Cohort'), cohortInstance.proposedCode])
            redirect cohortInstance
        }
        '*'{ respond cohortInstance, [status: OK] }
    }
}
Neal
  • 1

1 Answers1

0

In your update method definition (def update(Cohort cohortInstance) {}), you are initializing the instance of Cohort which is a new feature in grails 2.3.x, where grails automatically initializes the instance & do parameter binding for you .

Then again on line 4, you are getting the Cohort instance by using Cohort.get(params.id). So now you have two options: First is that, you can use read method instead of get and remove the auto initialization from the action signature or second is that, you can remove this line (cohortInstance = Cohort.get(params.id)) and add a Transactional annotation at update action like:

import grails.transaction.Transactional

@Transactional(readOnly = true)
def update(Cohort cohortInstance) {
  ...
}

Any of these work.

Shashank Agrawal
  • 25,161
  • 11
  • 89
  • 121