Grails/GORM 默认获取策略:何时将 fetchMode 设置为“eager"?(渴望与懒惰) [英] Grails/GORM default fetch strategy: When to set fetchMode to "eager"? (eager vs. lazy)

查看:15
本文介绍了Grails/GORM 默认获取策略:何时将 fetchMode 设置为“eager"?(渴望与懒惰)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

关于何时在域类中将 fetchMode 设置为eager"的一般准则是什么?fetchModeeager"与默认lazy"的优缺点?

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"?

请提供一些具体示例/用例,说明何时使用eager"(fetchMode=eager),何时不使用(fetchMode=lazy).

Please include some specific examples/use-cases showing when to use "eager" (fetchMode=eager), and when not to (fetchMode=lazy).

推荐答案

基本上懒加载比急切的替代方案(性能、资源的使用)有更多的好处.由于它是所有关系的默认 grails 设置(自 Grails 1.1 起),您通常不应将其配置为预先获取,除非您遇到某些问题.如:

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:

  • 在不同的休眠会话中共享域实例(例如,将域类实例放入 http 会话范围并从中访问属性时 - 例如用户)
  • 访问布局/视图中的域类实例时获取 LazyInitializationException
  • 如果您确定每次(或大部分时间)获取实例时都会访问某个关系属性,那么配置此关系以进行急切获取也是有意义的.

在处理庞大的数据库时,急切地获取可能非常危险.想象一个像这样的域类:

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
   }

}

当您读取任何 TreeNode 实例时,它会自动将域类的所有其他实例从数据库中提取到您的内存中.当有足够多的实例时,你可能会因为只获取 1 个实例而杀死你的应用程序.

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 设置为“eager"?(渴望与懒惰)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆