Count query using Hibernate criteria

Posted on 10-05-2013 12:37 by graham
This short tutorial shows how to perform a Hibernate criteria query that counts records matching some criteria conditions.

Executing the count query


To execute a count query, we need to set a projection to Projections.rowCount() on the Criteria object.
CountQuerySample.java
public Integer countUsers (String userName)
{
Criteria c = getHibernateTemplate().getSessionFactory().getCurrentSession().createCriteria(User.class);

// add filter on user's name
c.add(Restrictions.ilike("name", "%" + userName + "%"));

return ((Number)c.setProjection(Projections.rowCount()).uniqueResult()).intValue();
}

The whole magic is done by this line:
((Number)c.setProjection(Projections.rowCount()).uniqueResult()).intValue()
Comments

 

Add comment

Has this tutorial been helpful to you? Or do you see anything wrong? We appreciate your opinion!
Your comment:
Show formatting hints
HTML is disallowed, but in your text you can use the following markup
  • [code][/code] for a block of code
  • [tt][/tt] for inline code
  • [link]link href|link anchor[/link] for links
  • [b][/b] for bold text
Email:
+ Ask a question
If you have a technical question related to programming and computers, ask it here. Other users will help you solve it!
Unanswered questions
Share your knowledge by helping others solve their problems