Hibernate 如何使用count(*)

Java代码 复制代码 收藏代码
  1. public int getCount(String emailGroupId, String emailBatchId)
  2. throws HibernateException {
  3. Session session = HibernateUtil.currentSession();
  4. Transaction tx = session.beginTransaction();
  5. String hql = "select count(*) from EmailSendInfo where email_group_id = :emailGroupId and batch_id = :batchId";
  6. Query query = session.createQuery(hql);
  7. query.setString("emailGroupId", emailGroupId);
  8. query.setString("batchId", emailBatchId);
  9. /*
  10. * for (Iterator it = query.iterate(); it.hasNext();) { return
  11. * ((Integer) it.next()).intValue(); }
  12. */
  13. try {
  14. return ((Integer) query.iterate().next()).intValue();
  15. } catch (Exception e) {
  16. throw new HibernateException("");
  17. } finally {
  18. tx.commit();
  19. HibernateUtil.closeSession();
  20. }
  21. }
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();
        }
    }



Strings + Hibernate:
Java代码 复制代码 收藏代码
  1. //第一种方法:
  2. String hql = "select count(*) from User as user";
  3. Integer count = (Integer)getHibernateTemplate().find(hql).listIterator().next();
  4. return count.intValue();
  5. //第二种方法:
  6. String hql = "select count(*) from User as user";
  7. return ((Integer)getHibernateTemplate().iterate(hql).next()).intValue();
  8. //第三种方法:
  9. String hql = "select count(*) from User as user";
  10. Query query = getHibernateTemplate().createQuery( getSession(),hql);
  11. return ((Integer)query.uniqueResult()).intValue();   
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值