使用GORM和Grails无法保持多对多关系

时间:2018-08-18 07:24:23

标签: hibernate grails groovy many-to-many gorm

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

2 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

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中使用这些关系