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



spring+hibernate
//第一种方法:
  String hql = "select count(*) from User as user";
  Integer count = (Integer)getHibernateTemplate().find(hql).listIterator().next();
  return count.intValue();

//第二种方法:
 String hql = "select count(*) from User as user";
  return ((Integer)getHibernateTemplate().iterate(hql).next()).intValue();

//第三种方法:
 String hql = "select count(*) from User as user";
 Query query =  getHibernateTemplate().createQuery( getSession(),hql);
 return ((Integer)query.uniqueResult()).intValue(); 

你可能感兴趣的:(Hibernate,Spring,Java)