简体   繁体   English

在JPA Criteria API中订购

[英]Order in JPA Criteria API

My entity looks like: 我的实体看起来像:

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

1) I would like to order result list by property size and date. 1)我想按属性大小和日期订购结果列表。

The part of my code: 我的代码部分:

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

Of course the ".size" it wrong. 当然,“。size”是错误的。 How can I do it using criteria API? 如何使用标准API?

2) How to add Tags from tagsList and Author in criteria? 2)如何从tagsListAuthor中添加Tags

那这个呢?

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

The body of the buildCriteria method solved my problems: 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")));

Also addTags method: 另外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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM