The Wild

Hibernate Criteria Group By and Return Entity List

· 5 min read · Mammals

In this article
  1. Background: Criteria API and Grouping
  2. How to Return an Entity List with groupBy
  3. Choosing Between Entity List and Projection
  4. Common Problems and Solutions
  5. Hibernate Criteria vs HQL vs JPA Criteria
  6. Performance and Best Practices
  7. Frequently Asked Questions

Yes, you can use Hibernate's Criteria API with a groupBy clause and still return a list of entities, but only if you group by the entity's identifier (or a unique field) and use a projection that includes the entity itself. The standard approach is to use Projections.groupProperty or Projections.projectionList with Projections.distinct, then set the result transformer to CriteriaSpecification.ALIAS_TO_ENTITY_MAP or Transformers.aliasToBean if you need a custom DTO. However, if you group by non-identifier columns, Hibernate will return Object[] arrays or maps, not entities, because grouped rows no longer map 1-to-1 to a table row.

Background: Criteria API and Grouping

The Hibernate Criteria API (now deprecated in Hibernate 6 in favor of JPA Criteria) allows you to build queries programmatically. The groupBy method groups results by one or more properties, similar to SQL's GROUP BY. When you group, the result set contains one row per group, not per entity. For example, if you group by category, you get one row per distinct category, not per product. To return a list of entities, you must ensure each group corresponds to exactly one entity—which happens only when you group by the entity's primary key (or a unique natural key).

How to Return an Entity List with groupBy

Here is a concrete example using Hibernate 5.x (legacy Criteria):

Criteria criteria = session.createCriteria(Product.class);
criteria.setProjection(Projections.projectionList()
    .add(Projections.groupProperty("id"))
    .add(Projections.property("name"))
    .add(Projections.property("price")));
criteria.setResultTransformer(Transformers.aliasToBean(Product.class));
List<Product> products = criteria.list();

In this example, grouping by id returns one row per product, and the transformer maps the projected columns back to a Product instance. But note: the returned object is a transient copy, not managed by the session. If you need managed entities, you must load them separately or use a different approach.

For JPA Criteria (Hibernate 6+), the equivalent is:

CriteriaBuilder cb = entityManager.getCriteriaBuilder();
CriteriaQuery<Product> query = cb.createQuery(Product.class);
Root<Product> root = query.from(Product.class);
query.select(root).groupBy(root.get("id"));
List<Product> result = entityManager.createQuery(query).getResultList();

Here, selecting the root entity and grouping by the primary key works because each group is a single entity. This returns managed entities.

Choosing Between Entity List and Projection

If you need the full entity with all its fields, grouping by the primary key is the only safe way. If you need aggregated data (e.g., count, sum, average) alongside entity fields, you must use projections and accept a non-entity result. For example:

criteria.setProjection(Projections.projectionList()
    .add(Projections.groupProperty("category"))
    .add(Projections.count("id")));
List<Object[]> rows = criteria.list();

This returns a list of Object[] where each array holds the category and count. To convert to a DTO, use Transformers.aliasToBean with matching property names.

Common Problems and Solutions

  • Problem: org.hibernate.QueryException: could not resolve property: ... when grouping by a nested property. Solution: Use the full path, e.g., root.get("address.city") in JPA, or create an alias with createAlias in legacy Criteria.
  • Problem: Returning entities with groupBy yields duplicate or incomplete data. Solution: Ensure you group by the primary key and select the root entity (or all scalar properties). If you group by non-key columns, you cannot get a valid entity.
  • Problem: Lazy loading fails after grouping because the returned objects are detached. Solution: Use Hibernate.initialize() or fetch joins before grouping, or re-attach with session.update() if needed.
  • Problem: In Hibernate 6, legacy Criteria is removed. Solution: Migrate to JPA Criteria or Hibernate's Session.createSelectionQuery with HQL.

Hibernate Criteria vs HQL vs JPA Criteria

Hibernate's legacy Criteria API is deprecated since Hibernate 5.2 and removed in Hibernate 6.0. The modern alternatives are:

  • HQL (Hibernate Query Language): Use select p from Product p group by p.id – works fine and is type-safe if you use TypedQuery.
  • JPA Criteria: The standard, portable API. Use CriteriaQuery<Product> with groupBy on the ID.
  • Native SQL: For complex group-by queries, but you lose portability and must handle entity mapping manually.

If you are starting a new project, use JPA Criteria or HQL. If you maintain legacy code, you may still see the old API.

Performance and Best Practices

Grouping by primary key is efficient because it uses the primary key index. However, if you group by a non-indexed column, the database may perform a full table scan. Always check the generated SQL. Use setMaxResults and setFirstResult for pagination, but be aware that grouping with pagination can be tricky if you also need counts. For large datasets, consider using a database view or a DTO projection to reduce data transfer.

Another best practice: avoid returning full entities when you only need a few fields. This reduces memory usage and improves performance. Use projections or DTOs with Transformers.aliasToBean.

Frequently Asked Questions

Can I group by a non-primary key and still get an entity list?

No. Grouping by a non-unique column produces one row per group, which cannot be represented as a single entity. You would get duplicate or incomplete data. You must group by the primary key or a unique constraint to return entities.

How do I get a count with groupBy in Hibernate Criteria?

Use Projections.count in the projection list. For example, Projections.projectionList().add(Projections.groupProperty("category")).add(Projections.count("id")). The result is a list of Object[] or a DTO if you use a transformer.

Does groupBy in Hibernate Criteria return distinct entities?

If you group by the primary key, each group is unique, so the resulting entities are distinct. If you group by other columns, you may get duplicate entities if you also select the entity, but that is not a valid grouping.

What is the difference between groupBy and distinct in Criteria?

groupBy groups rows and allows aggregate functions. distinct removes duplicate rows from the result set. They are different: distinct does not allow aggregates. You can combine them, e.g., Projections.distinct(Projections.property("category")).

Is Hibernate Criteria deprecated?

Yes, the legacy org.hibernate.Criteria API is deprecated since Hibernate 5.2 and removed in Hibernate 6.0. Use JPA Criteria or HQL instead.

How do I get a list of entities with a group by and having clause?

In JPA Criteria, use query.groupBy(root.get("id")).having(cb.gt(cb.count(root), 1)). In legacy Criteria, use criteria.setProjection(Projections.projectionList().add(Projections.groupProperty("id")).add(Projections.count("id"))) and then add criteria.add(Restrictions.sqlRestriction("1=1"))? Actually, having is not directly supported in legacy Criteria; you need to use HQL or JPA Criteria.