JPA 标准中的顺序 API

Order in JPA Criteria API

我的实体看起来像:

 class News {
    private Long id;
    private Author author;
    private List<Tag> tagsList;
    private String title;
    private List<Comment> commentsList;
    private Date modificationDate;
}

1) 我想按 属性 大小和日期排序结果列表。

我的部分代码:

cq.select(from).distinct(true)
                .orderBy(cb.desc(from.get("commentsList.size")), cb.desc(from.get("modificationDate")));

当然是“.size”就错了。如何使用条件 API?

2) 如何在条件中从 tagsListAuthor 添加 Tags

这个呢?

.orderBy(cb.desc(cb.size(from.<Collection>get("commentsList"))), cb.desc(from.get("modificationDate")));

buildCriteria 方法的主体解决了我的问题:

   CriteriaQuery<News> cq = cb.createQuery(News.class);
    Root<News> news = cq.from(News.class);
    cq = cq.select(news).distinct(true);

    if (sc != null) {
        boolean authorExist = sc.getAuthorId() != null;
        boolean tagsExist = sc.getTagIdsSet() != null && !sc.getTagIdsSet().isEmpty();

        if (authorExist && !tagsExist) {
            cq.where(cb.in(news.get("author").get("id")).value(sc.getAuthorId()));
        } else if (!authorExist && tagsExist) {
            cq.where(cb.or(addTags(cb, news, sc)));
        } else {
            cq.where(cb.and(
                    cb.in(news.get("author").get("id")).value(sc.getAuthorId()),
                    cb.or(addTags(cb, news, sc))
            ));
        }
    }

    return cq.orderBy(cb.desc(cb.size(news.<Collection>get("commentsList"))),
            cb.desc(news.get("modificationDate")));

还有addTags方法:

 private static Predicate addTags(CriteriaBuilder cb, Root<News> news, SearchCriteria sc) {
    In<Object> in = cb.in(news.get("tagsSet").get("id"));

    for (Long id : sc.getTagIdsSet()) {
        in = in.value(id);
    }

    return in;
}