2011-11-29 12 views
8

私はテーブルPersonを持っていて、 "birthDate"がnullでなく、それらが学生である人をすべて数えたいとします。 は、私が2列持つと仮定:いくつかの基準を持つHibernateのカウント行

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

私は休止状態使用して、これをどのように行うことができますが..?

+1

を働いていますかこれは基本的なクエリです。あなたはHibernateのドキュメントを読んだことがありますか? http://docs.jboss.org/hibernate/core/3.6/reference/en-US/html/queryhql.html –

答えて

28
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(); 
+0

同じクエリでisDropoutの数も確認したい場合はどうなりますか? – Stephane

+1

2つの独立したカウントが必要な場合は、共用体またはサブクエリのいずれかを使用する必要があり、したがって休止状態でいくつかの別名を使用する必要があります。あなたは特定の基準をグループ化する必要があるので – Lawrence

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

場合、または1つだけカウント値を求めており、何のリストが返されない:

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

あなたはそのサイズを知るためにリスト全体を取り出していますか?基本的なHQLクエリで十分な場合にCriteriaを使用するのはなぜですか? –

+0

@JB Nizet私はおそらくリストを他のロジックのためにも使用しているからです。 – NimChimpsky

+4

文字列を連結するよりも基準を優先します.SQLを文字列として書き込む場合は、ちょっと休止状態の目的を打ち負かします。 – NimChimpsky

3
Number count = (Number) session.createQuery(
    "select count(p.id) from Person p" 
    + " where p.birthDate is not null and p.isStudent = true").uniqueResult(); 
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()); 
    } 
} 
+1

回答の一部だけでなく、回答を適切にフォーマットしてください。 – konqi

+1

「使用しています。動作しています」というのは役に立つコメントではありません。なぜ誰かが投稿された回答がうまくいかないと思いますか? –

1
int result= (int)((long)session.createQuery("select count(p) from User p where p.mobileNumber = :pMobileNumber") 
       .setParameter("pMobileNumber", mobileNumber).uniqueResult()); 
関連する問題