Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Count the rows in Hibernate Query Language?

I am trying to get just the count of the rows returned rather than all the results from the table.

I saw that this can be done like this:

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

But when trying to store this query in an integer format(it says cannot convert from Query to Integer)

I am using a dynamic query where the values will be mentioned below the query like this

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);

Now, how can i get a count of all the rows returned by using Hibernate query in a variable without using list.size but directly from the query?

like image 733
user1002782 Avatar asked Dec 30 '11 12:12

user1002782


3 Answers

Have you tried the query.uniqueResult(); ? As your Select count(*) will give you only one number, you should be able to retrieve it with this like int count = (Integer)query.uniqueResult();

To count based on a Criteria you can do this:

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

I'm using the Criteria right now so I know for sure that it works. I saw the uniqueResult() solution on a website here: http://www.jroller.com/RickHigh/entry/hibernate_pagination_jsf_datagrid_prototype1

like image 127
adreide Avatar answered Oct 20 '22 20:10

adreide


you can do this

long count = (long)session.createQuery("SELECT COUNT(e) FROM Employees e").getSingleResult();
like image 25
skyblue m. Avatar answered Oct 20 '22 19:10

skyblue m.


Try it.

Long count = ((Long) session.createQuery("select count(*) from Book").uniqueResult());
Integer totalBooks = count.intValue();
like image 6
Emiliano Dueñas Avatar answered Oct 20 '22 21:10

Emiliano Dueñas