Search code examples
hibernategrailsgrails-orm

How to get ScrollableResults with Gorm DetachedCriteria?


In Hibernate i can do:

// dc - DetachedCriteria
ScrollableResults sr = dc.getExecutableCriteria(getSession()).scroll()

But how to do the same with Gorm DetachedCriteria?

DomainName.withSession { session ->
    DomainName.where {
       // predicates
    }.getExecutableCriteria(session).scroll()
}

Code above will fail, because method not exists.

Updated: I have found this solution:

 def hiberSession = Holders.grailsApplication.mainContext.sessionFactory.currentSession
 def hiberDc = HibernateCriteriaBuilder.getHibernateDetachedCriteria(null, gormDc)
 def sr = hiberDc.getExecutableCriteria(hiberSession).scroll()

But the outgoing SQL has no columns in query:

select from domain_name where ... ;

Updated: I dug deeper and have found solution for previous problem.

hiberDc.setProjection(null)

Why this happens?

When you pass your detached criteria (gorm) to getHibernateDetachedCriteria and your detached criteria has no projections, then new detached criteria (hibernate) will have empty list of projections instead of null - proof.

Well, what of it?

Hibernate expects null in projection for generating all columns self - proof


Solution

  • So, answer to my question will be:

    def currentSession = Holders.grailsApplication.mainContext.sessionFactory.currentSession
    def hibernateDetachedCriteria = HibernateCriteriaBuilder.getHibernateDetachedCriteria(null, gormDetachedCriteria)
    def criteria = hibernateDetachedCriteria.getExecutableCriteria(currentSession)
    if (!criteria.projection) criteria.projection = null
    def scrollableResults = criteria.scroll(ScrollMode.FORWARD_ONLY)