Last editor: Dave Cherry, last modified: Aug 3, 2008
GORM makes mapping database relationships childs play, and mainly done by convention. Here we will discuss the most common mapping cases:
Lets start to build out our book object, and assume that we now need a Review object that links to Book. There are many reviews for each book, so therefore we map it with a many to one.
| Review (owned by Book) | |||
| Field | Type | Size | Constraint |
| Id | Long | 64bit | Primary Key |
| Author | String | 50 | Not blank |
| ReviewText | String | 10000 | Not blank |
So lets generate the Review object using the rules from the previous page:
class Review {
static belongsTo = [book:Book]
static constraints = {
author(maxSize:50, blank: false)
reviewText(maxSize:10000, blank: false)
}
String author
String reviewText
}
..and make the required changes to the Book object:
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)
}
String title;
String description;
String reference; int revision;
}
Here we have introduced two new static fields, hasMany = [property : Type] and belongsTo = [property : Type]. Fisrtly, hasMany describes the situation where the object will contain many refernces to another object. It uses the usual map syntax, so in the event there is more than one such mapping they are comma separated. By default a property will be added to the domain object with the same name as the map key.
Static field belongsTo describes the situation where the domain object is owned by another object. This means that when the owner object is deleted anything that belongsTo it will be too. This also uses the map syntax to describe the desired property name. An important feature of an object that belongsTo another is that transient instances of it will be saved along with the parent. See example below:
Book book = new Book(...populate fields...)
book.addToReviews(new Review(...populate fields...)
book.save()
If belongsTo was not used on Review, then the above would fail.