7.2.1.3 Many-to-many 2.4.4

See the light - agile, industrial strength, rapid web application development made easy

(Quick Reference) # 7.2.1.3 Many-to-many - Reference Documentation Authors: Graeme Rocher, Peter Ledbrook, Marc Palmer, Jeff Brown, Luke Daley, Burt Beckwith, Lari Hotari Version: 2.4.4 ## 7.2.1.3 Many-to-many 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 this 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 | Quick Reference (hide)