java examples
Home Java Examples Resources Java Interview Questions
Brainpower SEO

How to select a single record using 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 com.javacoderanch.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 com.javacoderanch.example.hibernate.model.Genre;

public class UniqueResultDemo {
    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.
            //
            Genre genre = (Genre) criteria.uniqueResult();
            
            System.out.println("Genre = " + genre.getName());
        } finally {
            session.close();
        }
    }
}