2012-02-07 42 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