我刚从 Grails 开始,这是第一个问题。
我花了几个小时才发现域对象不能插入 DB,直到它的所有属性都被填充。
class Item {
String title
String link
}
class ItemController {
def fetch = {
def item = new Item()
item.title = "blabla"
// no value for "link"
item.save()
}
}
看起来很合乎逻辑,但为什么它会如此无声地跳过?在这种情况下,我可以配置一些东西来获得异常(exception)吗?
谢谢
最佳答案
默认不抛出异常。save()
注入(inject)到域类的方法返回 false
如果在验证阶段发生错误。
用于检查域类的保存/更新的经典代码示例是:
if (!myDomainObj.save()) {
log.warn myDomainObj.errors.allErrors.join(' \n') //each error is an instance of org.springframework.validation.FieldError
}
如果您需要为特定域类设置异常,请使用:
myDomainObj.save(failOnError: true)
并且将抛出验证失败的异常。
如果你想为每个域类抛出异常,那么只需设置
grails.gorm.failOnError
至true
在 grails-app/conf/Config.groovy注意:所有域属性都有一个隐含的
nullable: false
约束。我推荐你阅读this article .
关于hibernate - 为什么 Grails 在域对象保存时不通知我错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4765037/