Search code examples
javasqlhibernatehibernate-criteria

Hibernate criteria order by one-to-many association count


I have an entity "X" with a one-to-many association to "Y"s

Each X has a unique xid, and each Y has an xid, and a unique yid

I want to write a criteria that produces a list of X's ordered by the number of associated Y's

Here is the equivalent SQL

SELECT * 
FROM X JOIN Y ON X.xid = Y.xid
GROUP BY X.xid
ORDER BY COUNT(Y.yid) DESC

How do I express this using Hibernate Criteria?

Many thanks Peter


Solution

  • You'll want to create an alias for the Y collection, get its count, and sort by it. Here is an example:

    // Create the criteria assuming session is open
    Criteria criteria = session.createCriteria(X.class, "x");
    
    // Give the Y association an alias
    criteria.createAlias("x.yCollectionName", "yCollectionAlias"); 
    
    // Get the count of IDs in the joined collection
    criteria.setProjection(Projections.projectionList().add(Projections.groupProperty("yCollectionAlias.id"))
    .add(Projections.count("yCollectionAlias.id").as("yCollectionAliasCount")));
    
    // Sort the criteria associated by Ys
    criteria.addOrder(Order.desc("yCollectionAliasCount"));