For older versions of Hibernate (<5.2):
Assuming the class name is Book:
return (Number) session.createCriteria("Book")
.setProjection(Projections.rowCount())
.uniqueResult();
It is at least a Number
, most likely a Long
.
In Java i usually need to return int and use this form:
int count = ((Long)getSession().createQuery("select count(*) from Book").uniqueResult()).intValue();
Here is what official hibernate docs tell us about this:
You can count the number of query results without returning them:
( (Integer) session.createQuery("select count(*) from ....").iterate().next() ).intValue()
However, it doesn't always return Integer
instance, so it is better to use java.lang.Number
for safety.
org.hibernate.dialect.function.StandardAnsiSqlAggregationFunctions.CountFunction
(StandardBasicTypes.LONG)
You could try count(*)
Integer count = (Integer) session.createQuery("select count(*) from Books").uniqueResult();
Where Books
is the name off the class
- not the table in the database.
If you are using Hibernate 5+, then query will be modified as
Long count = session.createQuery("select count(1) from Book")
.getSingleResult();
Or if you Need TypedQuery
Long count = session.createQuery("select count(1) from Book",Long.class)
.getSingleResult();
Long count = (Long) session.createQuery("select count(*) from Book").uniqueResult();
This works in Hibernate 4(Tested).
String hql="select count(*) from Book";
Query query= getCurrentSession().createQuery(hql);
Long count=(Long) query.uniqueResult();
return count;
Where getCurrentSession() is:
@Autowired
private SessionFactory sessionFactory;
private Session getCurrentSession(){
return sessionFactory.getCurrentSession();
}
It's very easy, just run the following JPQL query:
int count = (
(Number)
entityManager
.createQuery(
"select count(b) " +
"from Book b")
.getSingleResult()
).intValue();
The reason we are casting to Number
is that some databases will return Long
while others will return BigInteger
, so for portability sake you are better off casting to a Number
and getting an int
or a long
, depending on how many rows you are expecting to be counted.
Success story sharing
Object
.return (Number) session.createCriteria(Book.class).setProjection(Projections.rowCount()).uniqueResult();