我有一个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()
我的桌子上有作者和书籍,但没有关系。以下代码给出了空列表。
def author = Author.get(1)
def books = author.books
不知道我在想什么。我已经阅读了很多与此问题类似的答案,并且有人建议使用单独的连接类。但是我正在升级现有的应用程序,并且在很多地方都使用了addTo语法。所以我要坚持下去。至少,我想知道为什么这不起作用,因为这是标准实现。
我还显示了图像中生成的联接表结构。
看来联接表的结构也不是很正确。我的理解是,它应该使用键author_id和book_id创建一个名称为author_books的表。
最佳答案
您没有显示足够的上下文来确定,但是我希望保存是在有问题的上下文中进行的,这可能是因为未刷新 session 。一种验证方法是在保存时刷新 session 。
请参阅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.groovypackage prabinupretirelationship
class Book {
String title
static constraints = {
}
}
https://github.com/jeffbrown/prabinupretirelationship/blob/2fcf133f65309e449b408f4152f3a36fbb053a3e/grails-app/init/prabinupretirelationship/BootStrap.groovy(注意:我实际上不会这样做,但是我正在尝试使用与您所要求的方法接近的代码。更好的主意是将持久性逻辑移至GORM数据服务(http://gorm.grails.org/7.0.4/hibernate/manual/index.html#dataServices)中,在该处事务和 session 全部由GORM管理)。
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 = {
}
}
logSql
在https://github.com/jeffbrown/prabinupretirelationship/blob/2fcf133f65309e449b408f4152f3a36fbb053a3e/grails-app/conf/application.yml#L106设置为true
。运行该应用程序时,以下SQL语句将发送到数据库,包括填充联接表:
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 (?, ?)
关于grails - Grails具有许多关联未保存到联接表中,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/63593130/