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 = {
title(maxSize:50)
}
}


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

Slow, Buffering, Stuttering Udemy Video

Intellij tip - Joining multiple lines into one

Looking for IT work in Australia? JobReel.com.au!