Grails 有许多协会未保存加入 table

Grails hasMany associations not saving to join table

我有一个 Grails 4.0.3 应用程序。我只是开始测试一些域映射。看来我无法创建一对多和多对多的关系。现在我正在尝试一个简单的一对多关系。

这是我的实现:

    class Author {

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

class Book {

    String title

    static constraints = {
    }
}

我已经启动了:

def author = new Author('name':"Author")
        author.addToBooks(new Book('title':"Book1"))
        author.addToBooks(new Book('title':"Book2"))
        author.save()

我在 table 中有作者和书籍,但没有关系。

以下代码给出空列表。

def author = Author.get(1)
def books = author.books

不确定我错过了什么。我已经阅读了很多与此问题类似的答案,有些人建议使用单独的连接 class。但是我正在升级我现有的应用程序,并且有很多地方使用了 addTo 语法。所以我想坚持下去。 至少,我想知道为什么这不起作用,因为这是标准实现。

我还在图像中显示了生成的连接 table 结构。 join table 的结构似乎也不对。我的理解是它应该创建一个名称为 author_books 的 table,键为 author_id 和 book_id.

您没有显示足够的上下文来确定,但我希望保存发生在有问题的上下文中,可能是因为会话没有被刷新。一种验证方法是在保存时刷新会话。

https://github.com/jeffbrown/prabinupretirelationship 查看项目。

https://github.com/jeffbrown/prabinupretirelationship/blob/2fcf133f65309e449b408f4152f3a36fbb053a3e/grails-app/domain/prabinupretirelationship/Author.groovy

package prabinupretirelationship

class Author {

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

https://github.com/jeffbrown/prabinupretirelationship/blob/2fcf133f65309e449b408f4152f3a36fbb053a3e/grails-app/domain/prabinupretirelationship/Book.groovy

package prabinupretirelationship

class Book {

    String title

    static constraints = {
    }
}

https://github.com/jeffbrown/prabinupretirelationship/blob/2fcf133f65309e449b408f4152f3a36fbb053a3e/grails-app/init/prabinupretirelationship/BootStrap.groovy

(注意:我实际上不会这样做,但我正在尝试使用接近您询问的方法的代码。更好的主意是将持久性逻辑移动到 GORM 数据事务和会话都由 GORM 管理的服务 (http://gorm.grails.org/7.0.4/hibernate/manual/index.html#dataServices)。

package prabinupretirelationship

class BootStrap {

    def init = { servletContext ->
        Author.withTransaction {
            def author = new Author('name': "Author")
            author.addToBooks(new Book('title': "Book1"))
            author.addToBooks(new Book('title': "Book2"))
            author.save(flush: true)
        }
    }
    def destroy = {
    }
}

logSqlhttps://github.com/jeffbrown/prabinupretirelationship/blob/2fcf133f65309e449b408f4152f3a36fbb053a3e/grails-app/conf/application.yml#L106 处设置为 true

当应用程序 运行 时,以下 SQL 语句被发送到数据库,包括填充连接 table:

Hibernate: insert into author (id, version, name) values (null, ?, ?)
Hibernate: insert into book (id, version, title) values (null, ?, ?)
Hibernate: insert into book (id, version, title) values (null, ?, ?)
Hibernate: insert into author_book (author_books_id, book_id) values (?, ?)
Hibernate: insert into author_book (author_books_id, book_id) values (?, ?)