Search code examples
hibernategrailsgrails-orm

createAlias on a Detached Criteria (GORM)


For a Grails project, I need it to sort by field of associated entity. Like fetch entries sorted by authors name:

def crteria = new DetachedCriteria(Entry)
criteria.list {
  order('author.name', 'asc')
}

Current example will fail with:

org.hibernate.QueryException: could not resolve property: author.name of: Entry

It's common problem with Hibernate, and usually done by introducting an alias for author, like:

criteria.createAlias('author')
criteria.addOrder(Order.asc('author.name')) 

But the problem that Grails gorm.DetachedCriteria doesn't have such method, throws NoSuchMethodException. And I don't want to use plain hibernate.DetachedCritera instead, because need to support legacy code, written with Groovy criterias.

How I can add such alias? or how apply this sort w/o it?

Maybe there is a was to create a hibernate.DetachedCriteria, add alias, and then convert it to gorm.DetachedCriteria?

-

PS what's crazy, groovy order('author.name', 'asc') works fine for Integration tests. Fails only on a real app, grails run-app.


Solution

  • I believe you can get the DetachedCriteria from the GORM criteria builder any time and modify it with HibernateCriteriaBuilder.getHibernateDetachedCriteria(query).

    The GORM DetachedCriteria is only a builder interface for the underlying Hibernate DetachedCriteria.