0

将 GORM 与 Grails 3.3.6 一起使用,不会保持多对多关系。

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

重现步骤:

创建一个新应用程序:

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 打开 http://localhost:8080/dbconsolejdbc:h2:mem:devDb以查看生成的数据库。

4

2 回答 2

0

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

于 2018-08-20T07:13:17.820 回答
0

似乎是 GORM 工作方式的问题,请查看下一个链接

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 = {
    }
}

另外我建议您使用不同的域来处理多对多关系,因为在 GORM 中使用关系 是有害的

于 2018-08-20T23:20:44.423 回答