Search code examples
javasqlhibernatenhibernatehql

Sort by count HQL


I'm trying to sort Schools by the number of Students. There is a ManyToOne / OneToMany relationship between them.

This is not working but this is what I have so far

from School s order by count(s.students)

I would prefer not to use Criteria as I would have to refactor a lot of code. Is there a way to achieve this with HQL?


Solution

  • Ok I figured it out. This worked

    from School s order by size(s.students)

    As per the Hibernate documentation

    You can test the size of a collection with the special property size or the special size() function.