Grails GORM Criteria Query Eager Fetching

﹥>﹥吖頭↗ 提交于 2019-12-07 06:43:14

问题


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.


回答1:


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]


来源:https://stackoverflow.com/questions/14758499/grails-gorm-criteria-query-eager-fetching

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!