Chapter 9
[ 229 ]
If we model our domain directly in the database, we need to build and manage
tables, and make associations between the tables by using foreign keys. For complex
relationships, including many-to-many relationships, we may need to build
special tables whose sole function is to contain the foreign keys needed to track
the relationships between objects. Using GORM, we can model all of the various
associations that we need to establish between objects directly within the GORM
class definitions. GORM takes care of all of the complex mappings to tables and
foreign keys through a Hibernate persistence layer.
One-to-one
The simplest association that we need to model in GORM is a one-to-one association.
Suppose our customer can have a single address, we will create a new Address
domain class using the grails create-domain-class command, as before:
class Address {
String street
String city
}
To create the simplest one-to-one relationship with Customer, we just add an
Address field to the Customer class:
class CustomerHasAddress {
String firstName
String lastName
Address address
}
When we rerun the Grails application, GORM will recreate a new address table. It
will also recognize the address field of CustomerHasAddress as an association with
the Address class, and create a foreign key relationship between the customer and
address tables accordingly.
This is a one-directional relationship. We are saying that a Customer "has an"
Address but an Address class does not necessarily "have a" Customer.
We can model bi-directional associations by simply adding a Customer field to the
Address class. This will then be reflected in the relational model by GORM adding a
customer_id field to the address table:
class Address {
String street
String city
CustomerHasAddress customer
}