Karan Gujral Karan Gujral - 1 month ago 8
Java Question

Hibernate count rows with some criterias

Suppose I have a table Person and i want to count all those people whose "birthDate" is not null and they are a student.
Assuming i have two columns :

birthDate Date (can be null)
isStudent boolean (default: false)


How can i do this using hibernate.. ?

Answer
Criteria crit = session.createCriteria(Person.class);
crit.add( Restrictions.isNotNull("birthDate"));
crit.add( Restrictions.eq("isStudent", true));
crit.setProjection(Projections.rowCount());
Integer count = (Integer)crit.uniqueResult();