14

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

Karan Gujral
  • 389
  • 2
  • 4
  • 21
  • 1
    What have you tried? This is a basic query. Have you read the Hibernate documentation? http://docs.jboss.org/hibernate/core/3.6/reference/en-US/html/queryhql.html – JB Nizet Nov 29 '11 at 12:18

6 Answers6

48
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();
Khader M A
  • 5,423
  • 3
  • 19
  • 19
Lawrence
  • 1,035
  • 13
  • 8
  • What if he also wanted to see the count of isDropout in the same query ? – Stephane Mar 16 '16 at 12:16
  • 2
    If you want two independent counts you'll have to use either a union or a sub-query and thus some aliasing in hibernate. Because you need to group on specific criteria – Lawrence Jun 23 '17 at 14:57
18
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(); 
NimChimpsky
  • 46,453
  • 60
  • 198
  • 311
  • 2
    You're fetching the whole list just to know its size? Why use Criteria when a basic HQL query is sufficient? – JB Nizet Nov 29 '11 at 12:24
  • @JB Nizet because i would probably be using the list as well for other logic – NimChimpsky Nov 29 '11 at 12:26
  • 5
    I prefer criteria over concatenating strings, kinda defeats the purpose of hibernate if you write out sql as a string, imho. – NimChimpsky Nov 29 '11 at 12:38
  • The criteria is ok, but there's no reason to fetch all the results for a single count operation: think about when you have a query with 1,000+ results, it will take so much time for Hibernate to fill the list to only be interested in the number of results – McSonk Jul 11 '17 at 14:26
4
Number count = (Number) session.createQuery(
    "select count(p.id) from Person p"
    + " where p.birthDate is not null and p.isStudent = true").uniqueResult();
JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
1
int result= (int)((long)session.createQuery("select count(p) from User p where p.mobileNumber = :pMobileNumber")
                 .setParameter("pMobileNumber", mobileNumber).uniqueResult());
Jugal Panchal
  • 1,448
  • 16
  • 20
0

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());
    }
}
Vikdor
  • 23,934
  • 10
  • 61
  • 84
nitin
  • 9
  • 1
0
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

Ming Leung
  • 385
  • 2
  • 13