Hibernate以及Spring中如何使用count(*)取得表中记录总数方法



Hibernate以及Spring中如何使用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();

 

posted on 2008-05-29 14:59 重归本垒(Bing) 阅读(6430) 评论(1) 编辑 收藏 所属分类: JAVA

 

 

Comments

# re: Hibernate中如何使用count(*)取得表中记录总数

11

Iterator it=session.iterate(“select count(distinct obj)”+ hql,db.getObjects(),db.getTypes());

Integer count=(Integer)it.next();//这一步报错

page.setTotalItems(count.intValue());