Search code examples
grailsgrails-ormlazy-loadingfetcheager-loading

Grails / GORM: difference between lazy: false & fetchMode eager


In Grails / GORM, what is the difference between static mapping = {xyz lazy: false} & static fetchMode = [xyz: 'eager']?

Example:

class Book {
    static belongsTo = [author: Author]
    static mapping   = {author  lazy: false}
    static fetchMode = [author: 'eager']
}

Solution

  • The difference between lazy:false and fetchMode 'eager' are

    1. lazy:false will get the associated domain object by querying again to database using Select Query, but fetchMode 'eager' which is deprecated now(use fetch:'join') will try to join the associated tables(using outer join) and fetch the associated objects in single query.
    2. lazy:false will have one more query to the database to fetch the associated domain object and hence would be having more interactions with the database whereas fetch:'join' will have less interaction to fetch the same data.
    3. FetchMode Join overrides the lazy property. It will simple ignore the lazy:false.

    Should you be interested in a detailed explanation about Fetchmodes, take a look http://www.solidsyntax.be/2013/10/17/fetching-collections-hibernate/. The article describes the Hibernate fetchmodes and the output which they produce.

    Hope this helps.