【发布时间】: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