Just another WordPress.com site
Grails data binding is a simple tool that becomes really useful when having to assign values from request parameters to domain objects. Thanks to databinding assigning a whole bunch of properties can be done in one line of code:
Book book = new Book(params)
If the domain object already exists the equivalent is:
book.properties = params
If we have a domain object with many properties and with associations this can save loads of boilerplate code. As an example we are going to take a book domain class that has the following properties:
String name String isbn Date dateOfRelease Person author
Without data-binding assigning all those properties would mean having to do:
book.name = params.name book.isbn = params.isbn book.dateOfRelease = new Date().parse("dd-MM-YYYY", params.dateOfRelease)
It is important to notice the obvious fact that if we want to bind the parameters of a web request (for example the result of a form submission) automatically, we need to use the same names in the fields sent through the form as in the domain class. However applying this simple convention that may as well be positive to preserve consistency, the process of gathering the result of a web request and create a new domain object can be simplified to one sentence. No need to set the parameters one by one.
In the case of one to one associations data binding is even more useful because it avoids having to create the domain objects. Let’s say our initial book class has an author property whose type is Person. If we didn’t have databinding associating this new property would mean having to do:
def author = new Person() author.name = "John" book.author = author
While with databinding if we had our parameters map with this content:
params ["author.name"] = "John"
The person object would be created with its name and it would be associated to the book.author property automatically.
In this first article we’ve seen how databinding can help avoiding having to write boilerplate code, simplifying notably the task of creating domain objects. In following episodes we’ll see how databinding works for many ended associations and other benefits of this approach such as converting automatically from string to the appropriate data type thanks to Spring’s propertyEditors.