简体   繁体   中英

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.

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. How can I do it using criteria API?

2) How to add Tags from tagsList and Author in criteria?

那这个呢?

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

The body of the buildCriteria method solved my problems:

   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:

 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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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