blog rss feed

A guide to mapping databases in Grails with GORM

Keywords:

Last editor: Dave Cherry, last modified: Aug 3, 2008

Many to one mapping with GORM

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:

  1. Added a Category property to book, this automatically creates an appropriate link
  2. Added a hasMany field to category, indicating it has many books

Many to many mapping with GORM

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.

<< 1 2 3 4 5 >>

Please leave a comment



Search

Blog calendar

blog: previous month September 2010 blog: next month
su mo tu we th fr sa
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30