Hibernate 如何使用count(*)

public int getCount(String emailGroupId, String emailBatchId)             throws HibernateException ...{         Session session = HibernateUtil.currentSession();         Transaction tx = session.beginTransaction();         String hql = "select count(*) from EmailSendInfo where email_group_id = :emailGroupId and batch_id = :batchId";         Query query = session.createQuery(hql);         query.setString("emailGroupId", emailGroupId);         query.setString("batchId", emailBatchId);         /**//*          * for (Iterator it = query.iterate(); it.hasNext();) { return          * ((Integer) it.next()).intValue(); }          */         try ...{             return ((Integer) query.iterate().next()).intValue();         } catch (Exception e) ...{             throw new HibernateException("");         } finally ...{             tx.commit();             HibernateUtil.closeSession();         }     }

The select clause

The select clause picks which objects and properties to return in the query result set. Consider:

select mate 
     
     
from Cat as cat 
     
     
    inner join cat.mate as mate
     
     

The query will select mates of other Cats. Actually, you may express this query more compactly as:

select cat.mate from Cat cat
     
     

Queries may return properties of any value type including properties of component type:

select cat.name from DomesticCat cat
     
     
where cat.name like 'fri%'
     
     
select cust.name.firstName from Customer as cust
     
     

Queries may return multiple objects and/or properties as an array of type Object[],

select mother, offspr, mate.name 
     
     
from DomesticCat as mother
     
     
    inner join mother.mate as mate
     
     
    left outer join mother.kittens as offspr
     
     

or as a List,

select new list(mother, offspr, mate.name)
     
     
from DomesticCat as mother
     
     
    inner join mother.mate as mate
     
     
    left outer join mother.kittens as offspr
     
     

or as an actual typesafe Java object,

select new Family(mother, mate, offspr)
     
     
from DomesticCat as mother
     
     
    join mother.mate as mate
     
     
    left join mother.kittens as offspr
     
     

assuming that the class Family has an appropriate constructor.

You may assign aliases to selected expressions using as:

select max(bodyWeight) as max, min(bodyWeight) as min, count(*) as n
     
     
from Cat cat
     
     

This is most useful when used together with select new map:

select new map( max(bodyWeight) as max, min(bodyWeight) as min, count(*) as n )
     
     
from Cat cat
     
     

This query returns a Map from aliases to selected values.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值