2011-12-30 34 views
7

我想獲取返回的行數而不是表中的所有結果。如何計算Hibernate查詢語言中的行數?

我看到這個可以這樣做:

((Integer) session.createQuery("select count(*) from ....").iterate().next()).intValue() 

但是,試圖將存儲在一個整數格式(它說不能從Query to Integer轉換)這個查詢

當我使用的是動態查詢其中的值會提到下面的查詢這樣

theQuery = "select count(*) from THM as thm " + 
       "join thm.TMC as tmc " + 
       "join tmc.TIMCC as timcc " + 
       "where thm.Qid = :Qid and thm.Cv = :Cv and timcc.Did = :Did and timcc.Cv= :Cv"; 

Query query = session.createQuery(theQuery); 
query.setInteger("Qid", Integer.parseInt(Qid)); 
query.setInteger("Did", Did); 
query.setInteger("Cv",cV); 

現在,我怎樣才能通過在VA使用Hibernate查詢返回的所有行數riable沒有使用list.size但直接從查詢?

回答

13

你試過了query.uniqueResult(); ?由於你的選擇計數(*)只會給你一個數字,所以你應該可以用int count =(Integer)query.uniqueResult()來檢索它。

來算基於一個標準,你可以這樣做:

Criteria criteria = currentSession().createCriteria(type); 
criteria.setProjection(Projections.rowCount()); 
criteria.uniqueResult(); 

我使用的是標準,現在,所以我肯定知道,它的作品。我看到了一個網站,在這裏的uniqueResult()解決方案:http://www.jroller.com/RickHigh/entry/hibernate_pagination_jsf_datagrid_prototype1

+0

query.uniqueResult(); ()。next()).intValue() – user1002782 2012-01-05 13:21:54

+0

如果我的查詢不是Select count(*),而是像「from THM」開始的那樣, – Jerry 2017-05-10 06:44:09

7

你可以做到這一點

long count = (long)session.createQuery("SELECT COUNT(e) FROM Employees e").getSingleResult(); 
6

試試吧。

Long count = ((Long) session.createQuery("select count(*) from Book").uniqueResult()); 
Integer totalBooks = count.intValue();