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.criterion.Projections;
import org.hibernate.cfg.AnnotationConfiguration;
import org.kodejava.example.hibernate.model.Track;

import java.util.List;

public class ProjectionsCountDemo {
    private static final SessionFactory sessionFactory;

    static {
        try {
            sessionFactory = new AnnotationConfiguration().
        catch (Throwable ex) {
            throw new ExceptionInInitializerError(ex);

    public static Session getSession() throws HibernateException {
        return sessionFactory.openSession();

    public static void main(String[] args) {
        final Session session = getSession();
        try {
            Criteria criteria = session.createCriteria(Track.class)

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

Wayan Saryada

A programmer, runner, recreational diver, currently living in the island of Bali, Indonesia. Mostly programming in Java, creating web based application with Spring Framework, JPA, etc. If you need help on Java programming you can hire me on Fiverr.

Leave a Reply