Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hibernate count rows with some criterias

Tags:

java

hibernate

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.. ?

like image 595
Karan Gujral Avatar asked Nov 29 '11 12:11

Karan Gujral


2 Answers

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();
like image 85
Lawrence Avatar answered Sep 20 '22 04:09

Lawrence


Criteria crit = session.createCriteria(Person.class);
crit.add( Restrictions.isNotNull("birthDate"));
crit.add( Restrictions.eq("isStudent", true));
List<Person> students = crit.list();
Integer count = students.size();

or if just want a single count value, and no list returned :

Criteria crit = session.createCriteria(Person.class);
crit.setProjection(Projections.rowCount());
crit.add( Restrictions.isNotNull("birthDate"));
crit.add( Restrictions.eq("isStudent", true));
return (Long) crit.uniqueResult(); 
like image 35
NimChimpsky Avatar answered Sep 22 '22 04:09

NimChimpsky