The Wild

How to Add Distinct in Hibernate Criteria

· 4 min read · Mammals

In this article
  1. What You'll Need
  2. Step-by-Step
  3. Common Mistakes
  4. Tips
  5. Troubleshooting
  6. Frequently Asked Questions

To add DISTINCT to a Hibernate Criteria query, use setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY) or criteria.setResultTransformer(Transformers.distinctRootEntity()). This removes duplicate root entities from the result set, which is especially useful when you join to collections (like one-to-many) and get repeated parent rows. You can also use Projections.distinct() for scalar projections. This guide covers both approaches with clear steps, common pitfalls, and troubleshooting.

What You'll Need

  • A working Hibernate setup (version 3.x to 5.x; the API is the same for Criteria).
  • An entity class with a one-to-many or many-to-many relationship where duplicates appear.
  • Basic understanding of Hibernate Criteria API (creating a Criteria object, adding restrictions, etc.).

Step-by-Step

  1. Create a Criteria instance for your root entity, e.g., Criteria criteria = session.createCriteria(Order.class);
  2. Add joins or aliases that cause duplicates. For example, to join a collection: criteria.createAlias("items", "item"); or criteria.setFetchMode("items", FetchMode.JOIN); – this often produces duplicate root rows.
  3. Add your restrictions (where clauses) as usual, e.g., criteria.add(Restrictions.eq("status", "active"));
  4. Apply the distinct transformer before executing the query. Use one of these:
    • criteria.setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY);
    • or criteria.setResultTransformer(Transformers.distinctRootEntity()); (both are equivalent).
  5. Execute the query with criteria.list() or criteria.uniqueResult(). The returned list will contain unique root entities.
  6. For scalar projections (e.g., selecting specific columns), use Projections.distinct(Projections.property("name")) inside setProjection(). For example: criteria.setProjection(Projections.distinct(Projections.property("customerName"))); – this returns distinct values of that property.
  7. If you need distinct on multiple properties, wrap a ProjectionList inside Projections.distinct(): ProjectionList projList = Projections.projectionList(); projList.add(Projections.property("name")); projList.add(Projections.property("city")); criteria.setProjection(Projections.distinct(projList));

Common Mistakes

  • Using SELECT DISTINCT in HQL instead of Criteria – this guide is for Criteria API; HQL has its own syntax.
  • Applying DISTINCT_ROOT_ENTITY after a projection – if you use projections, the transformer may not work as expected; use Projections.distinct() instead.
  • Forgetting to add the transformer before calling list() – it must be set on the Criteria object before execution.
  • Expecting it to remove duplicates from child collections – DISTINCT_ROOT_ENTITY only deduplicates the root entities, not the associated children. If you need distinct children, you must query the child entity separately.
  • Using setResultTransformer with CriteriaSpecification.ALIAS_TO_ENTITY_MAP or other transformers – combining transformers can cause unexpected results; stick to one.

Tips

  • Check your SQL output – enable Hibernate SQL logging (hibernate.show_sql=true) to see if the generated SQL actually uses DISTINCT. The transformer may filter in memory, which can be inefficient for large datasets.
  • For performance, consider using HQL with SELECT DISTINCT – HQL pushes DISTINCT to the database, which is often faster than in-memory deduplication.
  • If you only need distinct values of one column, use Projections.distinct – it generates SQL-level DISTINCT and returns a list of scalars.
  • Be aware of pagination – if you use setFirstResult/setMaxResults with DISTINCT_ROOT_ENTITY, Hibernate applies the transformer after fetching the page, which can lead to fewer results than the page size. In such cases, you may need to use a subquery or HQL.
  • For Hibernate 5.2+, the Criteria API is deprecated in favor of JPA Criteria; consider migrating if you start a new project.

Troubleshooting

  • Duplicates still appear – ensure you are using the correct transformer. If you are using projections, you must use Projections.distinct() instead. Also check that you are not accidentally adding the transformer to a different Criteria object.
  • Query returns fewer rows than expected – this can happen when using DISTINCT_ROOT_ENTITY with pagination. The transformer filters after the database query, so the page may contain duplicates that are then removed, reducing the count. Use a subquery or HQL to avoid this.
  • ClassCastException when using projections – if you mix projections and DISTINCT_ROOT_ENTITY, the result type changes. Use Projections.distinct() for projections and DISTINCT_ROOT_ENTITY only for entity queries.
  • SQL shows no DISTINCT keyword – that is normal for DISTINCT_ROOT_ENTITY because it filters in memory. If you need SQL-level DISTINCT, use HQL or Projections.distinct().
  • Performance is slow – in-memory deduplication can be heavy for large result sets. Consider rewriting the query to avoid joins that cause duplicates, or use HQL with DISTINCT.

Frequently Asked Questions

Does DISTINCT_ROOT_ENTITY work with uniqueResult()?

Yes, but it is rarely needed. If you expect a single result, use uniqueResult() directly; if duplicates are possible, the transformer will filter them before returning, but you might get a NonUniqueResultException if multiple distinct entities remain.

Can I use DISTINCT_ROOT_ENTITY with setProjection?

No, it is designed for entity results. For projections, use Projections.distinct().

What is the difference between CriteriaSpecification.DISTINCT_ROOT_ENTITY and Transformers.distinctRootEntity()?

They are functionally identical. The first is a constant from CriteriaSpecification, the second is a convenience method from Transformers that returns the same transformer instance.

Does DISTINCT work with createAlias and setFetchMode?

Yes, both can cause duplicates. The transformer will deduplicate the root entities regardless of how the join is created.

Why does my query still return duplicate child collections?

DISTINCT_ROOT_ENTITY only removes duplicate root entities. If you need distinct children, you must query the child entity separately or use a DetachedCriteria subquery.

Can I use Projections.distinct on a property that is a collection?

No, projections are for scalar values, not collections. For distinct collections, you would need to query the child entity.