問:hibernate, select name, count(*) from table group by name。這句話應該怎麼用HQL語句執行?或者在hibernate中該怎麼查出每個name對應的count?
答:String hql = "select name, count(*) from table group by name"; //跟sql語句差不多的,不過這裏的name是類的屬性,table 是類名,因爲HQL是面向對象的查詢的語言。
首先要獲得session,你懂的,
然後 Query query = session.createQuery(hql);
List list = query.list();
獲取list裏面的name :
Iterator it = lits.iterator();
if(it.hasNext()){
Object[] obj = (Object[]) it.next();
String name = obj[0];
int count = obj[1];
}
在項目開發中的具體情況:
//關鍵是處理count映射問題。120221 hjl
String q = "select userId, nickName, count(id) from BbscsLogintimes where LoginYear = ? and LoginMonth = ? group by userId order by col_2_0_ desc";
Query query = session.createQuery(q);
query.setLong(0, Long.valueOf(year));
query.setLong(1, Long.valueOf(mon));
List list = query.list();
//封裝
List list2 = new ArrayList();
BbscsLogintimes logintimes= null;
Iterator it = list.iterator();
long j = 1;
while(it.hasNext()){
logintimes = new BbscsLogintimes();
Object[] obj = (Object[]) it.next();
logintimes.setOrderId(j);
logintimes.setOrderName((String) obj[1]);
logintimes.setOrderNum((Integer)obj[2]);
list2.add(logintimes);
j++;
}
說明:HQL別名字段
hibernate執行時打印出HQL
<property name="show_sql">true</property>
Hibernate: select bbscslogin0_.UserID as col_0_0_, bbscslogin0_.NickName as col_1_0_, count(bbscslogin0_.ID) as col_2_0_ from bbscs6.bbscs_logintimes bbscslogin0_ where LoginYear=? and LoginMonth=? group by bbscslogin0_.UserID order by col_2_0_ desc limit ?
UserID別名 ~ col_0_0_
NickName別名 ~ col_1_0_
count(bbscslogin0_.ID)別名 ~ col_2_0_
所以上面的HQL語句:group by userId order by col_2_0_ desc //按count統計量來降序排列。
<!-- 挪到後面去了 <span jwcid="@If" condition="prop:userCanSeeAnswerQuestion"> <div class="answer_question"><input id="meAnswer" value="我來回答" type="button"></input> </div> </span> --><!-- 除了 已解決還需要嗎?--><!-- 沒了 <span jwcid="@If" condition="ognl:userHasEditorTransferAuthority && questionBeTransered && !hiddenUserOpr" volatile="prop:true"> <div class="shift_record"> 轉移QQ號:<span jwcid="@Insert" value="prop:lastTransfererId">21993961</span> 時間:<span jwcid="@Insert" value="prop:lastTransferedTime">2008-08-27 17:34</span> </div> </span> -->