I need to update a row in DB whose id is known. But the number of fields to update is high and is a complex object. (ie) contains nested objects. Hence I am trying the below lines of code, but instead of update an insert happens
long myId // Primary key/id of row to be updated
DomainObject obj = gson.fromJson(jsonString, DomainObject.class)
obj.id=myId
obj.save(flush:true)
Please help why it doing insert instead of update. How to update a row (grails domain class) based on id ?
You can try this.
def gson = gsonBuilder.create()
// because the incoming JSON contains an id this will read the DomainObject
// from the database and update it!
def domainObjectInstance = gson.fromJson(request.reader, DomainObject)
domainObjectInstance.save();
Try updating your original object from DB with json attributes
long myId = 1
//load from DB
def o1 = DomainObject.get(myId)
//create object from json (or just create Map)
def o2 = gson.fromJson(jsonString, DomainObject)
//set all properties from json into object from DB
o2.properties.each { updateKey, updateValue ->
o1[updateKey] = updateValue
}
//save your original object to DB with new attributes
o1.save()
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.