Java – how to sort by count () in JPA
I am using this JPA query:
SELECT DISTINCT e.label FROM Entity e GROUP BY e.label ORDER BY COUNT(e.label) DESC
I didn't get an error, the result was almost correct, but there were some value errors (two values were flipped or some values were completely misplaced)
Edit:
Adding count (e.Label) to my select clause can solve this problem of this query
However, the where clause is also included in similar queries, and the problem still exists:
SELECT DISTINCT e.label,COUNT(e.label) FROM Entity e WHERE TYPE(e.cat) = :category GROUP BY e.label ORDER BY COUNT(e.label) DESC
Solution
You may need to include count (e.Label) in the select clause:
SELECT DISTINCT e.label,COUNT(e.label) FROM Entity e GROUP BY e.label ORDER BY COUNT(e.label) DESC
Update: for the second query, read section 8.6. Of the entitymanager documentation Polymer queries section It seems that if you query in a way that requires multiple selections, order by will no longer work This seems to be the case with the type keyword References to the above links:
The following query will return all persistent objects:
from java.lang.Object o // HQL only
The named interface may be implemented by various persistence classes:
from Named n,Named m where n.name = m.name // HQL only
Note that the last two queries will require multiple SQL SELECT This means that the order by clause does not correctly sort the entire result set (this also means that you cannot call these queries using query. Scroll().)