2012-06-20 35 views
0

我想知道是否有人知道如何從使用休眠標準查詢的單個查詢中獲得多個計數?hibernate標準查詢在單個查詢中獲得多個計數。

我有以下查詢。

List<PurchaseRequest> prs = this.session.createCriteria(PurchaseRequest.class).list(); 

在PurchaseRequest中,我有一個名爲current_state的列。我想查詢所有PurchaseRequest行並將current_states組合在一起,以便可以獲得每個current_state的總數。

各國看起來像這樣,創造者,授權者,轉讓者。等

+0

你的意思是'選擇current_state,count(*)來自PurchaseRequest Group By current_state'? – AlexS

+0

@AlexS是的,這正是我的意思。 –

回答

1

嘗試這種情況:

Criteria criteriaPurchaseRequest=this.session.createCriteria(PurchaseRequest.class); 

ProjectionList projectionList = Projections.projectionList(); 
projectionList.add(Projections.groupProperty("current_state")); 
projectionList.add(Projections.rowCount()); 

criteriaPurchaseRequest.setProjection(projectionList); 

List results = criteriaPurchaseRequest.list(); 

要獲得的結果:

List results = criteriaPurchaseRequest.list(); 
Map currentStateMap = new HashMap(); 
Iterator it=results.iterator(); 
while (it.hasNext()){ 
Object obj[]=(Object[])it.next();   
    CurrentState currentState = (CurrentState)obj[0]; 
    currentStateMap .put(currentState.getDescription().toLowerCase(), (Integer)obj[1]); 
} 

其中CurrentState是表示列current_state(記住,休眠正在與對象)的對象。

+0

我需要什麼才能投出結果才能獲得金額? –

+0

您是否可以嘗試以下查詢:「選擇current_state,sum(金額),count(*)來自PurchaseRequest Group By current_state,金額」? – esmoreno

+0

對不起,我是指伯爵。你有什麼似乎是正確的,我只是不知道如何讓它顯示從結果計數。如果我把groupProperty拉出來,我可以將它放到一個Long中,但是如果我重新添加組,它會中斷,我假定它會返回count的狀態,並且需要創建某種類型的對象,以便它可以被轉換至。只是不確定什麼組屬性會是。 –