在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以查看结果数据库。
发布于 2018-08-20 07:13:18
您需要使用@Transactional
注释控制器操作,以便将更改持久保存到数据库中。
发布于 2018-08-20 23:20:44
GORM如何工作似乎是一个问题,请查看下一个link
package mx.jresendiz27.gorm.test
class BootStrap {
def init = { servletContext ->
// https://docs.grails.org/3.0.x/guide/GORM.html#manyToMany
// works
new Author(name:"Stephen King")
.addToBooks(new Book(title:"The Stand"))
.addToBooks(new Book(title:"The Shining"))
.save()
// does not work, should use save in each author
new Book(title:"Groovy in Action")
.addToAuthors(new Author(name:"Dierk Koenig").save())
.addToAuthors(new Author(name:"Guillaume Laforge").save())
.save(flush:true, failOnError: true)
}
def destroy = {
}
}
此外,我还建议您使用不同的域来处理多对多关系,因为it's harmful要使用GORM中的关系
https://stackoverflow.com/questions/51906308
复制相似问题