然后查看休眠日志,我看到在实际更新 p 之前,
Grails 尝试获取与 p 相关的每条评论,每个评论一个查询
评论,保存的性能很糟糕
我无法重现。请参阅https://github.com/jeffbrown/peterchou 上的项目。
Comment.groovy
// grails-app/domain/demo/Comment.groovy
package demo
class Comment {
String text
}
Person.groovy
// grails-app/domain/demo/Person.groovy
package demo
class Person {
String name
static hasMany = [comments: Comment]
}
BootStrap.groovy
// grails-app/conf/BootStrap.groovy
import demo.*
class BootStrap {
def init = { servletContext ->
println 'Before saving instance'
def p = new Person(name: 'Peter')
.addToComments(text: 'Comment One')
.addToComments(text: 'Comment Two')
.addToComments(text: 'Comment Three')
.save(flush: true)
println 'Before retrieving instance'
def p2 = Person.get(p.id)
println 'Before updating instance'
p2.name = 'Peter Chou'
p2.save()
}
def destroy = {
}
}
运行时,会产生以下输出:
Before saving instance
Hibernate: insert into person (id, version, name) values (null, ?, ?)
Hibernate: insert into comment (id, version, text) values (null, ?, ?)
Hibernate: insert into comment (id, version, text) values (null, ?, ?)
Hibernate: insert into comment (id, version, text) values (null, ?, ?)
Hibernate: insert into person_comment (person_comments_id, comment_id) values (?, ?)
Hibernate: insert into person_comment (person_comments_id, comment_id) values (?, ?)
Hibernate: insert into person_comment (person_comments_id, comment_id) values (?, ?)
Before retrieving instance
Before updating instance
Hibernate: update person set version=?, name=? where id=? and version=?
编辑:
我在https://github.com/jeffbrown/peterchou/commit/8c1f6a289cc0a6cff54e5b9fb9d1fed3e19b9760 添加了一个控制器,如下所示:
// grails-app/controllers/demo/DemoController.groovy
package demo
class DemoController {
def index() {
def p = Person.get(1)
def numberOfComments = p?.comments?.size()
p.name = "Name With Time: ${new Date()}"
p.save(flush: true)
render "Person has ${numberOfComments} comments."
}
}
调用时,它向数据库发送 1 个查询以检索 Person 实例,另一个查询以检索 Comment 实例,最后向 person 表发送更新。
Hibernate: select person0_.id as id1_1_0_, person0_.version as version2_1_0_, person0_.name as name3_1_0_ from person person0_ where person0_.id=?
Hibernate: select comments0_.person_comments_id as person_c1_1_0_, comments0_.comment_id as comment_2_2_0_, comment1_.id as id1_0_1_, comment1_.version as version2_0_1_, comment1_.text as text3_0_1_ from person_comment comments0_ inner join comment comment1_ on comments0_.comment_id=comment1_.id where comments0_.person_comments_id=?
Hibernate: update person set version=?, name=? where id=? and version=?