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

3

14

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!

Unswear answered 7/2, 2012 at 22:3 Comment(0)
H
31

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.

Hoodwink answered 7/5, 2013 at 0:50 Comment(1)
Doesn't work for me :( groovy.lang.MissingMethodException: No signature of method: grails.gorm.CriteriaBuilder.resultTransformer() is applicable for argument types: (org.hibernate.transform.AliasToEntityMapResultTransformer) values: [org.hibernate.transform.AliasToEntityMapResultTransformer@7a78d380]Cabinetmaker
H
2
def topFiveList = []
topFiveUsers.each { rec ->
    topFiveList << [posts: rec[0], author: rec[1]]
}
Hypercorrection answered 8/2, 2012 at 5:44 Comment(0)
H
2
def converted = topFiveUsers.collect{ [posts: it[0], author: it[1]] }
Hypercorrection answered 8/2, 2012 at 5:50 Comment(3)
Thanks for the reply. Of course I can transform the result later on - that is what I am doing at the moment. Then again I want to skip the overhead of postprocessing the result set. I guess that somewhere in the hibernate code the very same transformation happens anyway...Unswear
Shortly after I posted, it occurred to me that you weren't interested in a two-step solution.Hypercorrection
No worries! Thank you anyway for your support! se is just great!Unswear

© 2022 - 2024 — McMap. All rights reserved.