为什么GORM不保存我的对象? [英] Why is GORM not saving my object?

查看:75
本文介绍了为什么GORM不保存我的对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我在Grails控制台中执行这段代码:

  def p = new Post(title:T); 
p.save(flush:true); //或p.save();

Post.count();

GORM不会抛出任何异常,但数据不会保存在我的数据库中。我做错了什么?

解决方案

这很可能违反了约束条件。将 failOnError:true 添加到保存方法参数中。那么当你的保存失败时你会得到一个异常。 (或者,您可以检查保存的返回值,如果它是false,则打印出 p.errors.allErrors()。)



验证和保存一起完成。如果您正在验证已经绑定到某个域对象的用户提交的数据,那么为了检查由于无效输入而导致的保存失败,惯用的操作是检查save的返回值;由于无效输入而失败并不是特殊的行为。如果您只想保存对象的内容,并希望在出现问题时抛出异常,请使用 failOnError



有关他们为什么设计GORM的理由,以便您需要这样做查看这篇文章。

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.

这篇关于为什么GORM不保存我的对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆