Grails queries with criteria: how to get back a map with column?

fluxon picture fluxon · Feb 7, 2012 · Viewed 7k times · Source

Is it possible, to query grails with criteria and receive a list of maps instead of a list of lists? I would like to have the column names in the results in order to then work with an 'associative array' rather then numeric array offsets. I currently do something like

    def topFiveUsers = BlogEntry.createCriteria().list {
        projections {
            count('id')
            groupProperty('author')
        }
        maxResults 5
    }

Which results in [[123, app.User:1][111, app.User:2][...]...], i.e. a list of lists. I would rather want something like [[posts:123, author: app.User:1][posts: 111, author app.User:2][...]...].

As always: help is highly appreciated!

Answer

Diamond Hands picture Diamond Hands · May 7, 2013

Use resultTransformer(). As the parameter use CriteriaSpecification.ALIAS_TO_ENTITY_MAP
The documentation and examples on this topic is scarce. But here's an example:

import org.hibernate.criterion.CriteriaSpecification

BlogEntry.withCriteria {
  maxResults 5
  resultTransformer(CriteriaSpecification.ALIAS_TO_ENTITY_MAP)
  projections {
    count('id', 'total')
    groupProperty('author', 'author')
  }      
}  

Note that alias is required for all projections. Otherwise, the resulting map consists of nulls.