Reputation: 19
I am using grails and I am trying to store 3 model object sequentially and these code has written in service class. one of the model object is not storing in database. I am using modelObject.save() in service class. Am I in wrong direction please correct me. Thanks.
Upvotes: 0
Views: 182
Reputation: 75671
You probably have a validation error in that instance. Instead of calling just save()
and assuming that everything is valid, add a validity check so you can report the error(s) or retry, e.g.
modelObject.save()
if (modelObject.hasErrors()) {
def errors = modelObject.errors
// do something here with the `errors`
}
else {
// do post-save work
}
There is another option that is recommended far too often and is almost always the wrong option, and that is to add failOnError:true
to the save()
call. It's bad logically when processing user-submitted data because you should expect mistakes, hacking attempts, etc., so in general a validation problem is not an exceptional occurrance and shouldn't trigger an exception.
A less theoretical reason why failOnError:true
is that you trigger an exception, which will affect performance when there are a lot of them because of the significantly higher number of stack frames when using Groovy (we've all seen plenty mile-long Groovy stacktraces) and there's a runtime cost to filling in that data. But you would almost never need any of that stacktrace data, only the errors
that occurred, and as you see above that's easily accessed without artificially slowing things down with exceptions.
Consider the analogous version using failOnError
:
try {
modelObject.save(failOnError:true)
// do post-save work
}
catch (ValidationException e) {
def errors = e.errors
// do something here with the `errors`
}
It's basically the same code as before except the order is reversed, and this one wastes cpu cycles and memory and affects the scalability of your server.
Upvotes: 1
Reputation: 1983
Use flush true :
domainObject.save(flush: true)
The flush: true forces Hibernate to persist all changes to the database right away. It corresponds to what is known as flushing the session.
For more details follow this link :http://spring.io/blog/2010/06/23/gorm-gotchas-part-1/
Thanks Hope this will help you.
Upvotes: 0