2012-02-07 31 views
13

是否有可能用条件查询grails并接收地图列表而不是列表列表?我希望在结果中包含列名,以便使用“关联数组”而不是数字数组偏移量。我目前做类似带标准的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][...]...]

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

回答

2
def topFiveList = [] 
topFiveUsers.each { rec -> 
    topFiveList << [posts: rec[0], author: rec[1]] 
} 
2
def converted = topFiveUsers.collect{ [posts: it[0], author: it[1]] } 
+0

感谢您的回复。当然,我以后可以改变结果 - 这就是我目前所做的。然后我又想跳过后处理结果集的开销。我想在hibernate代码中的某个地方会发生同样的转换...... – fluxon 2012-02-09 10:35:27

+0

在我发布之后不久,我发现你对两步解决方案不感兴趣。 – 2012-02-09 15:20:05

+0

不用担心!无论如何,谢谢你的支持! se太棒了! – fluxon 2012-02-09 20:53:14

30

使用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') 
    }  
} 

请注意,所有投影都需要别名。否则,结果地图由空值组成。

+0

辉煌而优雅。非常感谢谢尔盖。 – 2014-03-31 17:26:46

+0

优秀.......非常感谢您.... – akiong 2016-12-06 08:17:43