Building JPA Criteria API query - sorting by number of elements in collection

前端 未结 1 333
死守一世寂寞
死守一世寂寞 2021-01-18 15:49

I am having problem with building a query with JPA Criteria API.

Entities and significant properties:

@Entity
public class Post {
    @Id int id;
           


        
1条回答
  •  离开以前
    2021-01-18 16:47

    CriteriaBuilder.size(Expression) returns an Expression that you may use in the ORDER BY clause. This line of code:

    p.get("comments")
    

    ..returns a Path which extends Expression so it is safe to use the returned value as an argument to Collection.size().

    However, the previously quoted line of code is using a particular overloaded version of Path.get() which will make it impossible for the compiler to infer type parameter X. Instead, the type argument will be assumed to be Object. But Collection.size() has declared his Expression-parameter to be a "parameterized type" with an "upper bound" of Collection (this is not reflected accurately in the first reference to CriteriaBuilder.size() in my answer, StackOverflow insist on erasing the type from the method signature. Please see the JavaDocs instead!). So we must provide the type argument explicitly.

    Try this:

    cq.orderBy(cb.desc(cb.size(p.get("comments"))));
    

    0 讨论(0)
提交回复
热议问题