How do I use Hibernate’s criterion?

This example demonstrate the use of Hibernate’s criterion. This restriction will query for some record based on a collection of parameter defined for a specific property of the bean.

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

import java.util.List;

public class RestrictionInDemo {
    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 {
            // Create a Criteria an add an in constraint for the property id.
            // This in restrictions will return genre with id 1, 2, 3 and 4.
            Criteria criteria = session.createCriteria(Genre.class)
                    .add("id", new Long[] {1l, 2l, 3l, 4l}));

            List<Genre> result = criteria.list();

            for (Genre genre : result) {
                System.out.println(genre.getId() + "; " + genre.getName());
        } finally {

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 🥳

Leave a Reply

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