Grails/GORM default fetch strategy: When to set fetchMode to “eager”? (eager vs. lazy)

蓝咒 提交于 2019-12-18 04:16:08

问题


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).


回答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:

  • 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.



来源:https://stackoverflow.com/questions/654704/grails-gorm-default-fetch-strategy-when-to-set-fetchmode-to-eager-eager-vs

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!