How to Add Distinct in Hibernate Criteria
In this article
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-manyormany-to-manyrelationship where duplicates appear. - Basic understanding of Hibernate Criteria API (creating a
Criteriaobject, adding restrictions, etc.).
Step-by-Step
- Create a Criteria instance for your root entity, e.g.,
Criteria criteria = session.createCriteria(Order.class); - Add joins or aliases that cause duplicates. For example, to join a collection:
criteria.createAlias("items", "item");orcriteria.setFetchMode("items", FetchMode.JOIN);– this often produces duplicate root rows. - Add your restrictions (where clauses) as usual, e.g.,
criteria.add(Restrictions.eq("status", "active")); - 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).
- Execute the query with
criteria.list()orcriteria.uniqueResult(). The returned list will contain unique root entities. - For scalar projections (e.g., selecting specific columns), use
Projections.distinct(Projections.property("name"))insidesetProjection(). For example:criteria.setProjection(Projections.distinct(Projections.property("customerName")));– this returns distinct values of that property. - If you need distinct on multiple properties, wrap a
ProjectionListinsideProjections.distinct():ProjectionList projList = Projections.projectionList(); projList.add(Projections.property("name")); projList.add(Projections.property("city")); criteria.setProjection(Projections.distinct(projList));
Common Mistakes
- Using
SELECT DISTINCTin HQL instead of Criteria – this guide is for Criteria API; HQL has its own syntax. - Applying
DISTINCT_ROOT_ENTITYafter a projection – if you use projections, the transformer may not work as expected; useProjections.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_ENTITYonly deduplicates the root entities, not the associated children. If you need distinct children, you must query the child entity separately. - Using
setResultTransformerwithCriteriaSpecification.ALIAS_TO_ENTITY_MAPor 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/setMaxResultswithDISTINCT_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_ENTITYwith 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. UseProjections.distinct()for projections andDISTINCT_ROOT_ENTITYonly for entity queries. - SQL shows no DISTINCT keyword – that is normal for
DISTINCT_ROOT_ENTITYbecause it filters in memory. If you need SQL-level DISTINCT, use HQL orProjections.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.