Why is GORM not saving my object?

拈花ヽ惹草 提交于 2019-12-04 09:17:32

问题


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?


回答1:


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.




回答2:


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



来源:https://stackoverflow.com/questions/9177563/why-is-gorm-not-saving-my-object

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!