How do I set the fetch mode for Criteria association?

To set the fetching mode for association we can call the Criteria‘s setFetchMode() method. We can user the FetchMode.SELECT or FetchMode.JOIN.

package org.kodejava.example.hibernate.criteria;

import org.hibernate.*;
import org.hibernate.criterion.Restrictions;
import org.hibernate.cfg.AnnotationConfiguration;
import org.kodejava.example.hibernate.model.Recording;

import java.util.List;

public class FetchModeDemo {
    private static final SessionFactory sessionFactory;

    static {
        try {
            sessionFactory = new AnnotationConfiguration().
                    configure("hibernate.cfg.xml").
                    buildSessionFactory();
        }
        catch (Throwable ex) {
            throw new ExceptionInInitializerError(ex);
        }
    }

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

    @SuppressWarnings("unchecked")
    public static void main(String[] args) {
        final Session session = getSession();
        try {
            Criteria criteria = session.createCriteria(Recording.class)
                    .setFetchMode("artist", FetchMode.SELECT)
                    .setFetchMode("label", FetchMode.SELECT)
                    .add(Restrictions.eq("title", "Please Please Me"));

            List recordings = criteria.list();
            for (Recording recording : recordings) {
                System.out.println("Recording  = " + recording.getTitle());
                System.out.println("Artist     = " + recording.getArtist().getName());
            }

        } finally {
            session.close();
        }
    }
}

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().
                    configure("hibernate.cfg.xml").
                    buildSessionFactory();
        }
        catch (Throwable ex) {
            throw new ExceptionInInitializerError(ex);
        }
    }

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

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

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

How do I order the Criteria query resultset?

In this demo you’ll see how to order the resultset of out Criteria query. It can be done by adding the org.hibernate.criterion.Order into the Criteria object and we can either order the result in ascending or descending order.

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

import java.util.List;

public class CriteriaOrderDemo {
    private static final SessionFactory sessionFactory;

    static {
        try {
            sessionFactory = new AnnotationConfiguration().
                    configure("hibernate.cfg.xml").
                    buildSessionFactory();
        }
        catch (Throwable ex) {
            throw new ExceptionInInitializerError(ex);
        }
    }

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

    @SuppressWarnings("unchecked")
    public static void main(String[] args) {
        final Session session = getSession();
        try {
            Criteria criteria = session.createCriteria(Track.class)
                    .addOrder(Order.asc("title"))
                    .setFirstResult(0)
                    .setMaxResults(10);

            List tracks = criteria.list();
            for (Track track : tracks) {
                System.out.println("Track = " + track.getTitle());
            }
        } finally {
            session.close();
        }
    }
}