具有多对多关系的热切加载 - Grails (GORM)
每本书可以有许多作者。每个作者都可以写很多本书。
class Book {
static belongsTo = Author
static hasMany = [authors:Author]
}
class Author {
static hasMany = [books:Book]
}
现在我什么时候可以这样做:
def book = Book.get(id)
def authors = book.authors
现在我想我应该能够获取每个作者并获取与他相关的书籍:
authors.each {
it.books
}
你看,现在它会递归(导致 stackoverflow)。有谁知道它在进行急切获取时到底是如何工作的?
Each book can have many authors. And each author can author many books.
class Book {
static belongsTo = Author
static hasMany = [authors:Author]
}
class Author {
static hasMany = [books:Book]
}
Now when can I do:
def book = Book.get(id)
def authors = book.authors
Now I am thinking I should be able to take each author and get the books he is associated with:
authors.each {
it.books
}
You see now it would get recursive (leading to stackoverflow). Does anyone know how it exactly works, when it is doing eager fetch?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
无论是急切加载还是延迟加载,一旦加载了 Hibernate 管理的实例,它就会保留在 Hibernate Session 中,这是其一级缓存(如果您还配置了二级缓存,那么实例也会在那里,并且可能有如果之前已加载,则从那里来)。
因此,加载书籍后,然后加载其作者集合(默认情况下为 Set),每个作者的书籍都已在会话中,因此无需访问数据库。
提前加载映射集合使用初始 ResultSet 来获取顶级实例以及一个数据库查询中的子实例。延迟加载集合只需要第二个数据库查询来填充集合,但它的好处是仅在需要时加载集合。
Whether it's eagerly or lazily loaded, once a Hibernate-managed instance is loaded it's kept in the Hibernate Session, which is its 1st-level cache (if you've also configured a 2nd-level cache then instances will also be there and may have come from there if they were previously loaded).
So having loaded the book, and then having loaded its author collection (a Set by default), each author's book is already in the Session, so there's no need to go to the database.
Eagerly loading a mapped collection uses the initial ResultSet to grab the top-level instance plus the child instances in one database query. Lazily loading the collection just requires a 2nd database query to populate the collection but it has the benefit of only loading the collection if needed.
为了更清楚地说明,您可以参考 Burt Beckwith 撰写的博客 http://burtbeckwith.com/blog /?p=169 您还可以浏览博客中给出的演示链接。
For more clarity you can refer to the blog written by Burt Beckwith at http://burtbeckwith.com/blog/?p=169 and you can also go through the presentation link given in the blog.