JPM
JPM

Reputation: 9296

JSON Grail Groovy Update SQL

Using a Groovy script with grails and want to do an update to a record in the database. I do the basic get the object from JSON and convert it to the Domain class and then do save() on it. From what I understand since I am new to Groovy and grails the save should update if the "id" is already there. But I don't get that, I get the standard SQL error of "Duplicate entry '1' for key 'PRIMARY'". How do I fix this?

def input = request.JSON
def instance = new Recorders(input)
instance.id = input.getAt("id")
instance.save()

and my domain is:

class Recorders {

Integer sdMode
Integer gsmMode

static mapping = {
    id generator: "assigned"
}

static constraints = {
    sdMode nullable: true
    gsmMode nullable: true
}
}

Upvotes: 2

Views: 642

Answers (1)

Rob Hruska
Rob Hruska

Reputation: 120316

Instead of doing a new Recorders(input), you probably ought to get it:

def input = request.JSON
def instance = Recorders.get(input.getAt('id'))
instance.properties = input
instance.save()

Edit

(From your comment) If it doesn't exist and you want to insert it:

def input = request.JSON
def id = input.getAt('id')
def instance = Recorders.get(id)
if(!instance) {
    instance = new Recorders(id: id)
}
instance.properties = input
instance.save()

I don't use assigned id generators much, so I'm not sure if Grails will bind the id automatically (since it's expecting it to be assigned). If it does, you can probably remove the id: id from the Recorders() constructor.

Upvotes: 2

Related Questions