craftsman
craftsman

Reputation: 15623

How do we count rows using older versions of Hibernate (~2009)?

For example, if we have a table Books, how would we count total number of book records with hibernate?

Upvotes: 242

Views: 248498

Answers (8)

xrcwrn
xrcwrn

Reputation: 5327

Long count = (Long) session.createQuery("select count(*) from  Book").uniqueResult();

Upvotes: 6

Salandur
Salandur

Reputation: 6453

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.

Upvotes: 310

Jon Spokes
Jon Spokes

Reputation: 2599

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.

Upvotes: 12

Vlad Mihalcea
Vlad Mihalcea

Reputation: 153780

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.

Upvotes: 1

LucianoDemuru
LucianoDemuru

Reputation: 131

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();
}

Upvotes: 1

rajadilipkolli
rajadilipkolli

Reputation: 3601

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();

Upvotes: 6

Anthony
Anthony

Reputation: 12736

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.

Upvotes: 42

marioosh
marioosh

Reputation: 28566

In Java i usually need to return int and use this form:

int count = ((Long)getSession().createQuery("select count(*) from Book").uniqueResult()).intValue();

Upvotes: 102

Related Questions