If the record doesnt exist, it should insert. And if the record exists, Grails should do an update.
new MyEntity(attr1:'val1', attr2:'val2').saveOrUpdate()????
EDIT I have modified my code as per your suggestions:
List<NutDto> res = np.parseNutData(file.inputStream);
for(NutDto cellValue : res){
def nutInstance = NutData.get(cellValue.getIdd())
System.out.println("nutInstance = " + nutInstance);
if(nutInstance){
System.out.println("Exists : " + nutInstance);
nutInstance.foo=cellValue.getFoo()
nutInstance.bar=cellValue.getBar()
}
else{
System.out.println("Not Exists")
nutInstance = new NutData(idd:cellValue.getIdd(),
foo:cellValue.getFoo(),
bar:cellValue.getBar())
}
def saveres = nutInstance.save(failOnError: true);
println("saveres = " + saveres);
nutInstance.errors.each { println it }
}
Still its not updating. Its throwing errors.
Field error in object 'sps.NutData' on field 'idd': rejected value [123456-1234]; codes [sps.NutData.idd.unique.error.sps.NutData.idd,sps.NutData.idd.unique.error.idd,sps.NutData.idd.unique.error.java.lang.String,sps.NutData.idd.unique.error,nutData.idd.unique.error.sps.NutData.idd,nutData.idd.unique.error.idd,nutData.idd.unique.error.java.lang.String,nutData.idd.unique.error,sps.NutData.idd.unique.sps.NutData.idd,sps.NutData.idd.unique.idd,sps.NutData.idd.unique.java.lang.String,sps.NutData.idd.unique,nutData.idd.unique.sps.NutData.idd,nutData.idd.unique.idd,nutData.idd.unique.java.lang.String,nutData.idd.unique,unique.sps.NutData.idd,unique.idd,unique.java.lang.String,unique]; arguments [idd,class sps.NutData,123456-1234]; default message [Property [{0}] of class [{1}] with value [{2}] must be unique]
The values are not getting updated.
EDIT 2
package sps
class NutData {
String idd
String foo
String bar
static constraints = {
idd(blank:false, unique:true)
}
static mapping = {
table 'M_NUT_DATA'
version false
id generator: 'assigned', name: "idd", type: 'string'
foo column:'FOO_COL'
bar column:'BAR_COL'
}
String toString(){
return idd + '_' + foo
}
}
Dynamic finders are precisely available for this purpose.
Using findOrSaveBy* your first sample code would be written as such:
def entity = MyEntity.findOrSaveByAttr1AndAttr2( val1, val2 )
Documentation : http://grails.org/doc/latest/ref/Domain%20Classes/findOrSaveBy.html
A .save()
should do this all, but it depends on the way you created the object.
if you use new MyEntity(..)
grails will create the record, if you get the object from database, the save will do an update.
You could use the following code (replace Widget with your class/entity):
def widgetInstance = Widget.findByName('firstWidget') ?: new Widget(name: 'firstWidget').save(failOnError: true)
The argument to the save functions "failOnError: true" will ensure that the code will fail in case there is an error.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With