Hibernate count rows with some criterias

后端 未结 6 970
生来不讨喜
生来不讨喜 2021-02-07 15:16

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         


        
6条回答
  •  甜味超标
    2021-02-07 15:29

    Criteria crit = session.createCriteria(Person.class);
    crit.add( Restrictions.isNotNull("birthDate"));
    crit.add( Restrictions.eq("isStudent", true));
    List 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(); 
    

提交回复
热议问题