Search code examples
mysqlsqljpql

How order Entities by value from newly created object in JPQL select query?


So, I have the next JPQL query:

SELECT NEW GroupByBooksCount(g.genreId, g.genreName, COUNT(g.genreId))
FROM Genre g
JOIN Book b ON
     g.genreId = b.genreId
GROUP BY g.genreId

that return me object with 3 values:

genreId, genreName, booksCountInGenre

How can I sort my result by booksCountInGenre parameter using JPQL? Or maby there are some other ways to make this select?

Thanks!


Solution

  • So, I find the solution!

    To order result set by one of constructor parameters in JPQL just set to ORDER BY parameter in the same form as in construcnor. Like this

    SELECT NEW GroupByBooksCount(g.genreId, g.genreName, COUNT(g.genreId))
    FROM Genre g
    JOIN Book b ON
         g.genreId = b.genreId
    GROUP BY g.genreId
    ORDER BY COUNT(g.genreId) ASC
    

    It works for me!