Search code examples
hibernategrailsgroovymany-to-manygrails-orm

Many-To-Many relationship not persisted using GORM and Grails


Using GORM with Grails 3.3.6 a many-to-many relationship is not persisted.

I followed examples at http://gorm.grails.org/6.1.x/hibernate/manual/#gormAssociation (paragraph 5.1.3). Book and Author objects are persisted, but book_authors table is empty.

Steps to reproduce:

Create a new app:

grails create-app helloworld
cd helloworld
grails create-controller hello
grails create-domain-class Book
grails create-domain-class Author

Edithelloworld\grails-app\domain\helloworld\Book.groovy

package helloworld

class Book {
    static belongsTo = Author
    static hasMany = [authors:Author]
    String title
}

Edit helloworld\grails-app\domain\helloworld\Author.groovy

package helloworld

class Author {
    static hasMany = [books:Book]
    String name
}

Edit helloworld\grails-app\controllers\helloworld

package helloworld

class HelloController {

    def index() { 
        
        new Author(name:"Stephen King")
        .addToBooks(new Book(title:"The Stand"))
        .addToBooks(new Book(title:"The Shining"))
        .save()
    
    }
}

Then grails run-app and go to http://localhost:8080/hello. Open http://localhost:8080/dbconsole with URL jdbc:h2:mem:devDb to see the resulting database.


Solution

  • You need to annotate the controller action with @Transactional to have the changes persisted into the database.