Grails: Validate domain object failed when creating new object
When I created a new domain object and call sa开发者_运维百科ve command after validating, it failed and return an error that the id of object is null! But my Domain's id will be generated by database sequence automatically, so I didn't pass the Id value to it. How can I solve it?! Here is my code:
if (person.validate()) { // It is always false here
person.save()
} else {
// something here
}
Thank you so much!
Without your code it's hard to tell, but I'm assuming you have no constraints so you aren't expecting any issues. But there's an implicit not-null constraint for all fields unless you override it with nullable: true
so that's probably what's failing.
The reason the id is null is that it's only assigned after a successful save()
call.
I guess you have added a field called id in you Person Model class. Normally Grails will do it for you so you don't have to add it
Actually, you don't need to call validate()
before save()
, since save()
implicitly call validate
before it save the object. You can do it like this:
if (person.save(flush:true)) {
// Report success
} else {
// Report error
person.errors.each {
println it
}
}
About the cause of your problem, I think it's impossible to say without knowing your domain object.
精彩评论