PDA

View Full Version : help with hibernate and error checking



jasonwucinski
Jun 5th, 2011, 03:20 PM
hello everyone. i have a controller that adds records to a database. in my database table i have a field that is declared unique. i would like to write code that tries to enter a new record but if an error is thrown due to that field already existing, i would like to do an update instead. below is the code i have started working on. i can trap an error but i dont know how to distinguish one error from another. thanks



def students = new XmlSlurper().parseText(linkedinResponse)

inkedinID = "${students.id}"
linkedinFirstName = " ${students.'first-name'}"
linkedinLastName = " ${students.'last-name'}"

def b = new LinkedinProfile(firstName:linkedinFirstName, lastName:linkedinLastName, linkedinId:linkedinID)


if( !b.save(flush:true) ) {
b.errors.each {
//is there a way to get the specific error code here?
println it
}
}

thanks
jason

jasonwucinski
Jun 7th, 2011, 06:40 PM
no one knows how to get error codes out?

gwa
Jun 8th, 2011, 03:52 AM
Is hibernate have a "merge mode" that update existing line or create if not exist ?

jasonwucinski
Jun 8th, 2011, 11:01 AM
well, i was able to get something working. i'm not sure if this is the right way to do it but what i do is first check to see if the PK exist. if it does, then i issue an update, otherwise i do an insert. bellows is the code i use. if anyone has any feedback please let me know.



def alum = LinkedinProfile.findByLinkedinId(oNewAlum[0].'linkedinId')
int i=0
alum.each {
i++
}

if(i>0){
alum.firstName = oNewAlum[0].'firstName'
alum.lastName = oNewAlum[0].'lastName'
alum.industry = oNewAlum[0].'industry'
alum.save()
}else{
oNewAlum[0].save()
}
}