13

是否可以使用标准查询 grails 并接收地图列表而不是列表列表?我想在结果中包含列名,以便使用“关联数组”而不是数字数组偏移量。我目前正在做类似的事情

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

这导致[[123, app.User:1][111, app.User:2][...]...],即列表列表。我宁愿想要类似的东西[[posts:123, author: app.User:1][posts: 111, author app.User:2][...]...]

一如既往:非常感谢您的帮助!

4

3 回答 3

31

使用resultTransformer()。作为参数使用CriteriaSpecification.ALIAS_TO_ENTITY_MAP
关于这个主题的文档和示例很少。但这里有一个例子:

import org.hibernate.criterion.CriteriaSpecification

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

请注意,所有投影都需要别名。否则,生成的映射由空值组成。

于 2013-05-07T00:50:23.173 回答
2
def topFiveList = []
topFiveUsers.each { rec ->
    topFiveList << [posts: rec[0], author: rec[1]]
}
于 2012-02-08T05:44:19.177 回答
2
def converted = topFiveUsers.collect{ [posts: it[0], author: it[1]] }
于 2012-02-08T05:50:30.370 回答