Groovy for Domain-specific Languages - Second Edition

(nextflipdebug2) #1

Existing Groovy DSLs


[ 230 ]

These basic one-to-one associations can be inferred by GORM just by interrogating
the fields in each domain class. To denote ownership in a relationship, GORM uses
an optional static field applied to a domain class called belongsTo. Suppose we add
an Identity class to retain the login identity of a customer in the application. We
would then use:


class CustomerHasIdentity {
String firstName
String lastName
Address address
Identity identity
}

class Address {
String street
String city
}

class Identity {
String email
String password

static belongsTo = CustomerHasIdentity
}

Classes are first-class citizens in the Groovy language. When we declare
static belongsTo = Customer, what we are actually doing is
storing a static instance of a java.lang.Class object for the Customer
class in the belongsTo field. Grails can interrogate this static field at load
time to infer the ownership relation between Identity and Customer.

Here we have three classes: CustomerHasIdentity, Address, and Identity.
CustomerHasIdentity has a one-to-one association with both Address and
Identity through the address and identity fields. However, the ident field is
"owned" by CustomerHasIdentity as indicated in the belongsTo setting. What this
means is that saves, updates, and deletes will be cascaded to identity but not to
address, as we can see in the following code. The addr object needs to be saved and
deleted independently of CustomerHasIdentity, but id is automatically saved and
deleted in sync with Customer:


http://www.ebook3000.com
Free download pdf