How do I select a single record using Hibernate Criteria?

The Criteria.uniqueResult() method make it easier to query a single instance of a persistence object. When no persistence found this method will return a null value.

package org.kodejava.example.hibernate;

import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.criterion.Restrictions;
import org.kodejava.example.hibernate.model.Genre;

public class UniqueResultExample {
    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();
    }

    public static void main(String[] args) {
        final Session session = getSession();
        try {
            Criteria criteria = session.createCriteria(Genre.class)
                    .add(Restrictions.eq("id", new Long(1)));

            // Convenience method to return a single instance that matches the
            // query, or null if the query returns no results.
            Object result = criteria.uniqueResult();
            if (result != null) {
                Genre genre = (Genre) result;
                System.out.println("Genre = " + genre.getName());
            }
        } finally {
            session.close();
        }
    }
}

Wayan

Programmer, runner, recreational diver, live in the island of Bali, Indonesia. Mostly programming in Java, creating web based application with Spring Framework, Hibernate / JPA.

8 Comments

  1. Hi Balaji, the example above is about Criteria.uniqueResult() method, not the list() method. And the JavaDoc of the uniqueResult() method says it return a single instance that matches the query or null if the query returns no result.

  2. Hello there, I’m using last version of Hibernate, and it tells me that “The method createCriteria(Class) from the type SharedSessionContract is deprecate”. What can I do? Thanks a lot dude.

Leave a Reply