For example, if we have a table Books, how would we count total number of book records with hibernate?
8 Answers
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.
10 Comments
Object.return (Number) session.createCriteria(Book.class).setProjection(Projections.rowCount()).uniqueResult();In Java i usually need to return int and use this form:
int count = ((Long)getSession().createQuery("select count(*) from Book").uniqueResult()).intValue();
8 Comments
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.
4 Comments
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.
4 Comments
Long count = (Long) session.createQuery("select count(*) from Book").uniqueResult();
1 Comment
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();
}
Comments
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.