Imediava's Blog

Just another site

Data binding on grails – The basics

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: = 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.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() = "John" = author

While with databinding if we had our parameters map with this content:

params [""] = "John"

The person object would be created with its name and it would be associated to the 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.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: