例如,如果我们有一个表Books,我们如何用hibernate计算图书记录的总数?
当前回答
你可以试试count(*)
Integer count = (Integer) session.createQuery("select count(*) from Books").uniqueResult();
其中Books是类外的名称,而不是数据库中的表。
其他回答
对于Hibernate的旧版本(<5.2):
假设类名为Book:
return (Number) session.createCriteria("Book")
.setProjection(Projections.rowCount())
.uniqueResult();
它至少是一个数字,很可能是一个长。
你可以试试count(*)
Integer count = (Integer) session.createQuery("select count(*) from Books").uniqueResult();
其中Books是类外的名称,而不是数据库中的表。
Long count = (Long) session.createQuery("select count(*) from Book").uniqueResult();
在Java中,我通常需要返回int并使用这种形式:
int count = ((Long)getSession().createQuery("select count(*) from Book").uniqueResult()).intValue();
这在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();
}