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.hibernate;

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

public class UniqueResultExample {
    public static Session getSession() throws HibernateException {
        String cfg = "hibernate.cfg.xml";
        SessionFactory sessionFactory = new Configuration().configure(cfg)
        return sessionFactory.openSession();

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

            // 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());

Maven Dependencies


Maven Central Maven Central



  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

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