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)
                .buildSessionFactory();
        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

<dependencies>
    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-core</artifactId>
        <version>5.6.9.Final</version>
    </dependency>
    <dependency>
        <groupId>com.mysql</groupId>
        <artifactId>mysql-connector-j</artifactId>
        <version>8.0.33</version>
    </dependency>
</dependencies>

Maven Central Maven Central

Wayan

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.

    Reply
  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.

    Reply

Leave a Reply to IgorCancel reply

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