按计数排序 HQL

Sort by count HQL

我正在尝试按 Student 的数量对 School 进行排序。它们之间存在 ManyToOne / OneToMany 关系。

这不起作用,但这是我目前所拥有的

from School s order by count(s.students)

我不想使用 Criteria,因为我必须重构大量代码。有没有办法用 HQL 来实现这个?

这应该有效 (期望 schoolstudent 之间存在关系,如 student.School:

//from School s order by count(s.students)
FROM School s 
ORDER BY (
  SELECT count(st) FROM Student st WHERE s.ID = st.School.ID 
)

好的,我明白了。这有效

from School s order by size(s.students)

根据 Hibernate 文档

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