例如,如果我们有一个表Books,我们如何用hibernate计算图书记录的总数?
当前回答
Long count = (Long) session.createQuery("select count(*) from Book").uniqueResult();
其他回答
以下是官方hibernate文档告诉我们的:
查询结果不返回,可以统计查询结果个数:
( (Integer) session.createQuery("select count(*) from ....").iterate().next() ).intValue()
但是,它并不总是返回Integer实例,因此为了安全起见,最好使用java.lang.Number。
你可以试试count(*)
Integer count = (Integer) session.createQuery("select count(*) from Books").uniqueResult();
其中Books是类外的名称,而不是数据库中的表。
如果您正在使用Hibernate 5+,那么查询将被修改为
Long count = session.createQuery("select count(1) from Book")
.getSingleResult();
或者如果你需要TypedQuery
Long count = session.createQuery("select count(1) from Book",Long.class)
.getSingleResult();
对于Hibernate的旧版本(<5.2):
假设类名为Book:
return (Number) session.createCriteria("Book")
.setProjection(Projections.rowCount())
.uniqueResult();
它至少是一个数字,很可能是一个长。
这在Hibernate 4(已测试)中有效。
String hql="select count(*) from Book";
Query query= getCurrentSession().createQuery(hql);
Long count=(Long) query.uniqueResult();
return count;
其中getCurrentSession()为:
@Autowired
private SessionFactory sessionFactory;
private Session getCurrentSession(){
return sessionFactory.getCurrentSession();
}