21 March 2008

Two ways to model One-to-Many in GORM

There are two subtly different, but distinct ways to model a One-to-Many relationship in GORM, each with some rather interesting implications.

Method One:
   1:class Book{
2: String title
3: static belongsTo = Author
4:}
5:
6:class Author {
7: String name
8: static hasMany = [books: Book]
9:}

This method results in the schema:


Furthermore, the following applys:
  1. An additional "link" table (author_book) will be created in the database.
  2. A books property will be available on Author
  3. There is no direct way of querying the reverse of the relationship. i.e. no straightforward way to lookup an Author if you're holding a Book object.(See this post for a solution)

Method Two:
   1:class Book{
2: String title
3: static belongsTo = Author
4: Author author
5:}
6:
7:class Author {
8: String name
9: static hasMany = [books: Book]
10:}
Note: The addition of "author" property at line 4 above.

This method results in the schema:



Furthermore:
  1. An additional column called author_id will be created on the Book table in the database
  2. No "link" table will be created in the database
  3. It is possible to query both the forward and reverse relationship by refering to the Books.author and Author.books properties respectively
FIN.

1 comments:

Nils said...

You can also use

static belongsTo = [author: Author]

where the key of the map is the attribute in the domain class to be used for the relationship.