From the Grails documentation, by default one-to-many relationships are represented using a join table.
I don't understand why this is desirable. I had little SQL experience before starting to use Hibernate and/or Grails' GORM. It seems like using a foreign key in the 'many'-side table pointing at a row on the 'one'-side table is the way to implement a one-to-many relationship...
Can anyone explain this sort of design decision?
The reason for using an join table for a unidirectional one-to-many relationship is because the many side of the relationship may have many relationships and does not know of those relationships. Perhaps an example is best here:
class Book {
String title
}
class BookStore {
String name
static hasMany = [books: Book]
}
class Library {
String name
static hasMany = [books: Book]
}
In the above domain, a Book
has no need to have both the BookStore
and Library
IDs on it's table. A Book
is perfectly valid without either. By using join tables this keeps from polluting the book table with foreign keys.
Keep in mind because this is modeling uni-directional and not bi-directional relationships.