将 GORM 与 Grails 3.3.6 一起使用,不会保持多对多关系。
我遵循了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 打开 http://localhost:8080/dbconsolejdbc:h2:mem:devDb以查看生成的数据库。