您没有显示足够的上下文来确定,但我希望保存发生在有问题的上下文中,可能是因为会话没有被刷新。验证这一点的一种方法是在保存时刷新会话。
在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 数据服务中(@987654325 @) 其中事务和会话都将由 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 (?, ?)