使用 GORM 和 Grails 不持久存在多对多关系

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

将 GORM 与 Grails 3.3.6 结合使用,不会持久化多对多关系。

我遵循了 http://gorm.grails.org/6.1.x/hibernate/manual/#gormAssociation 中的示例(第 5.1.3 段)。 Book 和 Author 对象被持久化,但是 book_authors table 是空的。

重现步骤:

创建新应用:

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

编辑helloworld\grails-app\domain\helloworld\Book.groovy

package helloworld

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

编辑helloworld\grails-app\domain\helloworld\Author.groovy

package helloworld

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

编辑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()
    
    }
}

然后 grails run-app 并转到 http://localhost:8080/hello。使用 URL jdbc:h2:mem:devDb 打开 http://localhost:8080/dbconsole 以查看生成的数据库。

您需要使用 @Transactional 注释控制器操作才能将更改持久保存到数据库中。

似乎是 GORM 工作方式的问题,检查下一个 link

package mx.jresendiz27.gorm.test

class BootStrap {

    def init = { servletContext ->
        //  https://docs.grails.org/3.0.x/guide/GORM.html#manyToMany
        // works
        new Author(name:"Stephen King")
        .addToBooks(new Book(title:"The Stand"))
        .addToBooks(new Book(title:"The Shining"))
        .save()
        // does not work, should use save in each author
        new Book(title:"Groovy in Action")
        .addToAuthors(new Author(name:"Dierk Koenig").save())
        .addToAuthors(new Author(name:"Guillaume Laforge").save())
        .save(flush:true, failOnError: true)
    }
    def destroy = {
    }
}

我还建议您使用不同的域来处理多对多关系,因为 it's harmful 使用 GORM 中的关系