Grails / GORM默认获取策略:何时将fetchMode设置为“渴望”? (渴望与懒惰) [英] Grails/GORM default fetch strategy: When to set fetchMode to "eager"? (eager vs. lazy)
问题描述
关于何时将fetchMode设置为域名类中的渴望的一般准则是什么? fetchModeeager与默认的lazy的优缺点?
请包括一些特定的示例/用例,说明何时使用eager(fetchMode = (fetchMode = lazy)。
基本上,懒加载比渴望替代,资源的使用)。由于它是所有关系的默认grails设置(自Grails 1.1以来),除非遇到某些问题,否则通常不应将其配置为提前提取。例如:
在处理大型数据库时,提前取指可能会相当危险。想象一下这样一个Domain类:
//非常糟糕的例子
类TreeNode {
字符串名称
TreeNode父元素
static hasMany = [childNodes:TreeNode]
静态映射{
父类型lazy:false
childNodes lazy:false
}
}
when您阅读任何TreeNode实例,它会自动将数据库中的所有其他域类实例都拉入内存。当有足够的实例时,您可能会通过仅提取1个实例来杀死您的应用程序。
What are some general guidelines on when to set fetchMode to "eager" in a domain class? Pros and cons of fetchMode "eager" vs. the default "lazy"?
Please include some specific examples/use-cases showing when to use "eager" (fetchMode=eager), and when not to (fetchMode=lazy).
Basically lazy loading has more benefits than the eager alternative (performance, use of resources) . Since it's the default grails setting for all relations (since Grails 1.1) you should generally not configure it for eager fetching, unless you experience certain issues. Such as:
- Sharing a domain instance accross different hibernate sessions (eg. when putting a domain class instance into the http session scope and accessing properties from it - such as a User)
- Getting LazyInitializationException when accessing domain class instances in layouts/views
- When you're sure, you will access a certain relation property everytime (or most of the time) when an instance is fetched, it would also make sense to configure this relation for eager fetching.
Eager fetching can be quite dangerous when dealing with huge databases. Imagine a Domain class like this:
// really bad example
class TreeNode {
String name
TreeNode parent
static hasMany = [ childNodes: TreeNode ]
static mapping {
parent lazy: false
childNodes lazy: false
}
}
when you read any of the TreeNode instances, it will automatically pull all other instances of the domain class from the database into your memory. When there are enough instances, you'll probably kill you application by fetching only 1 instance.
这篇关于Grails / GORM默认获取策略:何时将fetchMode设置为“渴望”? (渴望与懒惰)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!