【问题标题】:Many-To-Many relationship not persisted using GORM and Grails使用 GORM 和 Grails 未保持多对多关系
【发布时间】:2018-08-18 07:24:23
【问题描述】:

在 Grails 3.3.6 中使用 GORM,不会保持多对多关系。

我遵循了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 以查看生成的数据库。

【问题讨论】:

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


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

      似乎是 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 中的关系

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多