Last editor: Dave Cherry, last modified: Aug 3, 2008
Now we need to add a Category to our book object, which is a many to one relation. Before we go any further lets define category:
| Category | |||
| Field | Type | Size | Constraint |
| Id | Long | 64bit | Primary Key |
| Name | String | 100 | Not blank |
First we create the domain object using grails
grails create-domain-class Category..and from the above definition, we generate the following:
class Category {
static constraints = {
name(maxSize: 100, blank: false)
}
static hasMany = [books : Book]
String name;
}
..and finally we change Book so that it has a Category:
class Book {
static hasMany = [ reviews : Review ]
static constraints = {
title(maxSize:200, blank: false)
description(maxSize:20000, blank: false)
reference(size:10..16, blank: false)
revision(range: 1..20)
}
Category category;
String title;
String description;
String reference; int revision;
}
For simple cases thats it, we have mapped category onto book, and provided a collection of Book objects that is available from Category. Note that in this case neither object takes an owner role. Looking at the code the only changes to add category to book were:
If you've used Hibernate before, you may be used to mapping many-to-many tables in an invisible way, at the moment GORM does not provide this. Instead the join table must be included in your domain model; then you use the many-to-one and one-to-many support we've already seen.
For example if added a 'Keywords' object that linked to many Books, and each Books could have many Keywords, we would create a new domain object something like KeywordBookLink that had a one-to-one link with both Keyword and Book. In addition it would be wise to make either Book or Keyword the owner of the link object.