Main problem with non-working approach is calling methods of Java classes from JPQL query - that is not expected to work.
Assuming that significant properties of entities are roughly as follows:
@Entity
public class Post {
@Id int id;
@OneToMany (mappedBy = "post") List<Comment> comments;
//...
}
@Entity
public class Comment {
@Id int id;
@ManyToOne Post post;
//...
}
Then following should be enough with Hibernate+MySQL combo:
SELECT p
FROM Post p
ORDER BY SIZE(p.comments) DESC
JPA 2.0 specification requires bit more complex query, because what can be used in ORDER BY clause is rather limited:
- A state_field_path_expression that evaluates to an orderable state field of an entity or embeddable class abstract schema type designated
in the SELECT clause by one of the follow- ing: • a
general_identification_variable • a
single_valued_object_path_expression
- A state_field_path_expression that evaluates to the same state field of the same entity or embeddable abstract schema type as a
state_field_path_expression in the SELECT clause
- A result_variable that refers to an orderable item in the SELECT clause for which the same result_variable has been specified. This may
be the result of an aggregate_expression, a scalar_expression, or a
state_field_path_expression in the SELECT clause.
Following query should work also with other implementations. It is of course little bit tedious that additional variable is part of the result then:
SELECT p, SIZE(p.comments) as ord
FROM Post p
ORDER BY ord DESC