Hibernate计算具有一些标准的行

时间:2011-11-29 12:14:54

标签: java hibernate

假设我有一个表人员,我想要计算那些“birthDate”不为空且他们是学生的人。 假设我有两列:

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

我如何使用hibernate来实现这个目的..?

6 个答案:

答案 0 :(得分:32)

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();

答案 1 :(得分:13)

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();

或者只是想要一个计数值,并且没有返回列表:

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(); 

答案 2 :(得分:3)

Number count = (Number) session.createQuery(
    "select count(p.id) from Person p"
    + " where p.birthDate is not null and p.isStudent = true").uniqueResult();

答案 3 :(得分:1)

int result= (int)((long)session.createQuery("select count(p) from User p where p.mobileNumber = :pMobileNumber")
                 .setParameter("pMobileNumber", mobileNumber).uniqueResult());

答案 4 :(得分:0)

使用它。它的工作

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());
    }
}

答案 5 :(得分: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();

(Long)crit.uniqueResult()将导致NonUniqueResultException。 我检查了crit.list()。它是一个包含2个项目的ArrayList。 arraylist的第一项包含计数。第二项始终包含0。它是rowCount的预期结果吗?

谢谢