【发布时间】:2014-01-27 03:39:17
【问题描述】:
我在使用 JPA Criteria API 构建查询时遇到问题。
实体和重要属性:
@Entity
public class Post {
@Id int id;
@OneToMany (mappedBy = "post") Set<Comment> comments;
//...
}
@Entity
public class Comment {
@Id int id;
@ManyToOne Post post;
//...
}
我需要一个查询,该查询将返回 db 中按 cmets 数量排序的所有帖子(Post 中的OneToMany)。
起初我认为这可以用JPQL 来实现,比如:
SELECT p
FROM Post p
ORDER BY SIZE(p.comments) DESC
但是函数SIZE(...)不能被它在JPQL中排序。
所以,我找到了JPA Criteria API,并尝试了以下操作:
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<Post> cq = cb.createQuery(Post.class);
Root<Post> p = cq.from(Post.class);
cq.select(p);
cq.orderBy(cb.desc(p.get("comments")));
List<Post> resultList = em.createQuery(cq).getResultList();
通过此查询,我没有得到正确的结果。我知道我错过了获取集合'cmets'的size,但不知道如何添加该部分。我对JPA Criteria API 不是很熟悉。该查询应该如何查看按其comments 字段(集)的大小排序的所有帖子?
【问题讨论】:
-
你确定这行不通吗:
cq.orderBy(cb.desc(cb.size(p.<Collection>get("comments"))));? -
否则我认为您将不得不使用
Subquery和CriteriaBuilder.count(Expression)。 -
@MartinAndersson 是的,你是对的,我错过了
<Collection>部分,所以cq.orderBy(cb.desc(cb.size(p.<Collection<Comment>>get("comments"))));是正确的。您可以将此作为答案发布。谢谢。
标签: java hibernate jpa orm jpql