Hibernate 使用GORM和Grails不能持久化多对多关系
将GORM与Grails3.3.6一起使用时,不会持久化多对多关系 我遵循了(第5.1.3段)中的示例。Book和Author对象被持久化,但Book_authors表为空 复制步骤: 创建新应用程序:Hibernate 使用GORM和Grails不能持久化多对多关系,hibernate,grails,groovy,many-to-many,gorm,Hibernate,Grails,Groovy,Many To Many,Gorm,将GORM与Grails3.3.6一起使用时,不会持久化多对多关系 我遵循了(第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 编辑hello
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
}
package helloworld
class Author {
static hasMany = [books:Book]
String name
}
编辑helloworld\grails app\domain\helloworld\Author.groovy
package helloworld
class Book {
static belongsTo = Author
static hasMany = [authors:Author]
String title
}
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运行app
并转到http://localhost:8080/hello. 打开http://localhost:8080/dbconsole 使用URLjdbc:h2:mem:devDb
查看结果数据库。您需要使用@Transactional
注释控制器操作,以便将更改持久化到数据库中。似乎是GORM工作方式的一个问题,请检查下一步
我还建议您使用不同的域来处理多对多关系,因为要在GORM中使用关系