Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Grails/GORM default fetch strategy: When to set fetchMode to "eager"? (eager vs. 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"?

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

like image 968
knorv Avatar asked Mar 17 '09 15:03

knorv


1 Answers

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.

like image 181
Siegfried Puchbauer Avatar answered Sep 26 '22 15:09

Siegfried Puchbauer