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

Viewed 247873

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

8 Answers

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.

Related