What to do when your domain class won't save

When developing with Grails and GORM, if a domain class fails validation when calling the save() method, you won't get an exception - save() just returns false! This is mentioned in the Gotchas page and to find out what went wrong, it suggests looking in the errors.allErrors property of your domain class.

To do this, would go something like this:

if(book.save()) {
log.info("Book saved : ${book.title}")
} else {
log.info("FAILED: book save failed")
book.errors.allErrors.each { error ->
println error

If your book class had a constraint such as:

class Book {
String title static constraints = {

and you set the title to be more than 50 characters, you'd see an error message:
<the value of title> exceeds the maximum size of [50]

So, remember to check the boolean returned from save().

You can find out how to enforce constaints on your domain objects in the validation documentation - notice that some of these constraints are marked with 'influences schema generation'.

Popular posts from this blog

Using the Crystal Reports Java API to generate PDF

No Scope registered for scope request

Using Selenium WebDriver to select JSF/PrimeFaces selectOneMenu options