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.