Groovy for Domain-specific Languages - Second Edition

(nextflipdebug2) #1
Chapter 9

[ 237 ]

Composition

Composition is used when, instead of having separate tables for each business
object, we would like to embed the fields of a child object in the table of its parent.
In the previous one-to-one examples, it might be useful for us to have Address and
Identity classes to pass around in our Groovy code, but we may prefer the data for
these to be rolled into one database table. To do this, all we need to do is to add an
embedded setting to the Customer domain class, and GORM takes care of the rest:


class Customer {
String firstName
String lastName
Address billing
Address shipping
Identity ident
static embedded = ['billing','shipping','ident']
}

class Address {
String street
String city
}

class Identity {
String email
String password
}

We can see a useful application of embedding in the previous code snippet, where
we needed two addresses—one for billing and one for shipping. This does not
warrant a full one-to-many association between Customer and Address because
we only ever have the two addresses. The fields from Address and Identity get
mapped into columns in the customer table.

Free download pdf