Data Binding and One-To-Many AssociationsData Binding in Grails is referred to as the process of binding incoming request data, typically only available as key/value string pairs, to some domain object. Let's take a look at the BlogController's save closure out of an example project I've been showing at the last Austrian EJUG meeting : The second line in the
saveclosure creates an instance of the
Blogclass. As you might already know, creating objects can be done in multiple ways when working with Groovy. In this case, we use Groovy's feature to invoke the "default constructor" and bind the given map containing property values immediately to the fresh instance. However, when updating an already persisted
bloginstance we need to use a mechanism provided by Grails: the
propertiesproperty. You can use the
propertiesproperty to assign a map of key/value pairs to a domain class instance, thus updating the object. By the way: Grails uses Spring's data binding capabilities to perform data binding . This means that you can use all the possibilities provided by Spring, e.g. defining custom
PropertyEditorclasses. So far so good. But what happens when it comes to binding many-to-one or one-to-one associations? The answer is pretty simple: it just works .
GrailsDataBindereven supports lazy object instantiation of domain classes. Whenever the other side of the association does not exist, it is created by Grails and populated with the given request parameter values: But what happens when working with unidirectional one-to-many associations? In my EJUG example we had such a one-to-many association between a
BlogPostinstances. The design decision was to keep all domain class relationships as lean as possible, therefore we decided that a relationship between a blog post and its blog is not necessary, as the
Blogis a domain aggregate . A bit of digging into Grails'
bindCollectionAssociation: As you can see in the code snippet above, whenever the given property value
vis an array, it assumes that it is an array of identifiers. Than it iterates over the identifiers and tries to associate an object for the current identifier with the associated type retrieved via
associateObjectForIdit uses MOP programming to invoke the associations
addTo*method: Given a one-to-many association this means that we can simply use Grails default data binding functionality to bind this type of associations. In the view we could use a multi select box to map all selected blog post identifiers to a single request parameter: As a result, the
propertiesproperty can be used to automatically bind one-to-many associations. The only requirement is the array type which is important to notice when constructing the identifiers list manually:
ConclusionData Binding in Grails is based on Spring's validation and data binding mechanisms. When binding unidirectional one-to-many associations the
GrailsDataBinderautomatically associates objects due to the given identifiers.