Why is GORM not saving my object?

2019-03-14 19:51发布

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?

2条回答
何必那么认真
2楼-- · 2019-03-14 20:32

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

查看更多
冷血范
3楼-- · 2019-03-14 20:36

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.

查看更多
登录 后发表回答