How do I count the total records using Projections?

The example below show how to get total row count using the Projections.rowCount(). The result of this query will be a single object of Integer that contains the result of executing an SQL select count (*) command.

package org.kodejava.example.hibernate.criteria;

import org.hibernate.SessionFactory;
import org.hibernate.Session;
import org.hibernate.HibernateException;
import org.hibernate.Criteria;
import org.hibernate.cfg.Configuration;
import org.hibernate.criterion.Projections;
import org.kodejava.example.hibernate.model.Track;

import java.util.List;

public class ProjectionsCountDemo {
    public static Session getSession() throws HibernateException {
        String cfg = "hibernate.cfg.xml";
        SessionFactory sessionFactory = new Configuration().configure(cfg)
            .buildSessionFactory();
        return sessionFactory.openSession();
    }

    @SuppressWarnings("unchecked")
    public static void main(String[] args) {
        try (Session session = getSession()) {
            Criteria criteria = session.createCriteria(Track.class)
                .setProjection(Projections.rowCount());

            List result = criteria.list();
            if (!result.isEmpty()) {
                Long rowCount = (Long) result.get(0);
                System.out.println("Total records: " + rowCount);
            }
        }
    }
}

Wayan Saryada

Founder at Kode Java Org
I am a programmer, a runner, a recreational diver, currently live in the island of Bali, Indonesia. Mostly programming in Java, Spring Framework, Hibernate / JPA. You can support my works by donating here. Thank you ?

2 Comments

    • Hi Dybuk,

      You can use the JPA Criteria API as the replacement for the deprecated Hibernate API.

      EntityManagerFactory factory =
          Persistence.createEntityManagerFactory(PERSISTENCE_UNIT_NAME);
      EntityManager em = factory.createEntityManager();
      
      CriteriaBuilder builder = em.getCriteriaBuilder();
      CriteriaQuery<Long> query = builder.createQuery(Long.class);
      query.select(builder.count(query.from(Track.class)));
      
      Long count = em.createQuery(query).getSingleResult();
      System.out.println("count = " + count);
      
      Reply

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.