Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Grails GORM Criteria Query Eager Fetching

I have written a criteria query in a Grails service class where I expect an eager join to be performed, and to avoid lazy loading of child objects when displaying my results either as a JSON response or in my GSP. The query executed as expected (setting my hibernate.show_sql=true in my DataSource.groovy I can see the query), but when I crawl the association in my GSP, I can see that Hibernate is executing subsequent queries as if it were lazily loading the associations. I'm not convinced that the eager loading is actually working. I do not want to set lazy:false within my domain class for these associations.

This is the criteria query:

def market = Market.withCriteria(uniqueResult:true){
    idEq(marketId)
    fetchMode 'resourceAssignments', FetchMode.JOIN
    fetchMode 'resourceAssignments.userRole', FetchMode.JOIN
    fetchMode 'resourceAssignments.userRole.role', FetchMode.JOIN
    fetchMode 'resourceAssignments.userRole.user', FetchMode.JOIN
    resourceAssignments{
        userRole{
            role{
                'in'('name', roleNames)
            }
        }
    }           
}

The above query returns without any issues. When I attempt to run the following code, though, in my GSP, I can see that Hibernate is issuing a second query as if it were lazily fetching the resourceAssignments:

<g:each in="${market.resourceAssignments}" var="ra">
</g:each>

I even tried overriding the OpenSessionInViewInterceptor with a No-Op interceptor, by creating an empty WebRequestInterceptor and setting the openSessionInViewInterceptor in the resources.groovy to use it. Once I did that, I get a org.hibernate.LazyInitializationException which seems to verify what I was thinking - that Hibernate or GORM is still trying to execute a second query even when I've specified that I want to eagerly fetch these associations.

like image 996
David Malone Avatar asked Feb 07 '13 18:02

David Malone


1 Answers

It appears to be a Grails bug with criteria queries. Here's an HQL query that works though:

def market = Market.executeQuery(
    'select m from Market m ' +
    'inner join fetch m.resourceAssignments as ra ' +
    'inner join fetch ra.userRole as ur ' +
    'inner join fetch ur.role as role ' +
    'inner join fetch ur.user as user ' +
    'where m.id=:marketId and role.name in (:roleNames)',
    [marketId: marketId, roleNames: roleNames], [max: 1])[0]
like image 200
Burt Beckwith Avatar answered Nov 04 '22 09:11

Burt Beckwith