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 :
birthDat
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();
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();
Use it. It's working
public class IncIncidentListGridModel
{
private String historyStatus = null;
public String getHistoryStatus()
{
return historyStatus;
}
public void setHistoryStatus(String historyStatus)
{
this.historyStatus = historyStatus;
}
public void run()
{
IncIncidentListGridModel resultCount =
(IncIncidentListGridModel) ((SQLQuery) hibersession
.createSQLQuery("select count(ch.incident_capa_history_id) as historyStatus from incident_capa_history ch, incident_capa ic where ic.incident_capa_id = ch.FK_incident_capa_id and ic.incident_capa_id='011'"))
.addScalar("historyStatus", Hibernate.STRING)
.setResultTransformer(
Transformers.aliasToBean(IncIncidentListGridModel.class))
.uniqueResult();
System.out.println("count result" + resultCount.getHistoryStatus());
}
}
int result= (int)((long)session.createQuery("select count(p) from User p where p.mobileNumber = :pMobileNumber")
.setParameter("pMobileNumber", mobileNumber).uniqueResult());
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();
The (Long)crit.uniqueResult() will cause NonUniqueResultException. I check the crit.list(). It is an ArrayList having 2 items. The first item of the arraylist contains the count. The second item always contains a 0. Is it the expected result of rowCount?
Thanks
Number count = (Number) session.createQuery(
"select count(p.id) from Person p"
+ " where p.birthDate is not null and p.isStudent = true").uniqueResult();