Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is GORM not saving my object?

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?

like image 690
K Everest Avatar asked Feb 07 '12 13:02

K Everest


2 Answers

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.

like image 83
Nathan Hughes Avatar answered Oct 07 '22 12:10

Nathan Hughes


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

like image 20
Stephen Swensen Avatar answered Oct 07 '22 11:10

Stephen Swensen