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

前端 未结 1 512
余生分开走
余生分开走 2020-12-17 01:52

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 inclu

相关标签:
1条回答
  • 2020-12-17 02:41

    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.

    0 讨论(0)
提交回复
热议问题