Dónal
Dónal

Reputation: 187499

Grails eager dynamic finder

If I load a list of domain classes using a dynamic finder, e.g.

List<Book> books = Book.findAllByPublicationYear(2013)

My understanding is that the list of books will be lazily loaded, such that if I then iterate over them

books.each { println "$it.title" }

I will execute N + 1 queries. Is there a way to make the dynamic finder eagerly load the list of books (without rewriting the query using HQL or criteria)?

Upvotes: 0

Views: 1273

Answers (1)

dmahapatro
dmahapatro

Reputation: 50245

Dynamic Finder is always eager fetch for (non-associated) members of the domain. For example, if publicationYear being a part of Book you will always run one query to get all the books matching the plublicationYear. My query looks like

select this_.id as id0_0_, this_.version as version0_0_, 
this_.name as name0_0_,this_.publication_year as publicat4_0_0_ 
from book this_ 
where this_.publication_year=?

In case you have an association in Book say (Author) you can programmatically say in the domain class whether you want to fetch the association eagerly or lazily by using this mapping:(default is lazy)

static mapping = {
        author lazy: false //or authors if you have multiple authors for a Book
    }

or

static fetchMode = [author: 'eager']

Upvotes: 4

Related Questions