Grails supports many-to-many relationships by defining a
hasMany
on both sides of the relationship and having a
belongsTo
on the owned side of the relationship:
class Book {
static belongsTo = Author
static hasMany = [authors:Author]
String title
}
class Author {
static hasMany = [books:Book]
String name
}
Grails maps a many-to-many using a join table at the database level. The owning side of the relationship, in this case
Author
, takes responsibility for persisting the relationship and is the only side that can cascade saves across.
For example this will work and cascade saves:
new Author(name:"Stephen King")
.addToBooks(new Book(title:"The Stand"))
.addToBooks(new Book(title:"The Shining"))
.save()
However the below will only save the
Book
and not the authors!
new Book(name:"Groovy in Action")
.addToAuthors(new Author(name:"Dierk Koenig"))
.addToAuthors(new Author(name:"Guillaume Laforge"))
.save()
This is the expected behaviour as, just like Hibernate, only one side of a many-to-many can take responsibility for managing the relationship.
Grails' Scaffolding feature does not currently support many-to-many relationship and hence you must write the code to manage the relationship yourself