If I execute this code in the Grails console:
def p = new Post(title: "T");
p.save(flush: true); // or p.save();
Post.count();
GORM is not throwing any exceptions, but the data is not saved in my DB. What am I doing wrong?
It's likely you have a constraint violation. Add failOnError: true
to your save method parameters. Then you'll get an exception when your save fails. (Alternatively you can check the return value from save, and if it's false print out p.errors.allErrors()
.)
Validation and saving are done together. If you are validating user-submitted data that's been bound to some domain object, then in order to check for the save failing due to invalid input the idiomatic thing to do is check the return value of save; failing on account of invalid input is not exceptional behavior. If you just want to save the contents of the object and want an exception thrown if there's a problem, use failOnError
.
For more on the rationale on why they designed GORM so that you need to do this see this article.
Likely some constraint on Post
is being violated and thus the object is not being saved. Note that the default behavior of GORM is not to throw on a failed save. You need to either call it like
p.save(flush: true, failOnError: true);
Or change the behavior globally by adding
grails.gorm.failOnError=true
to your Config.groovy
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