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.
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With