【问题标题】:Order in JPA Criteria APIJPA Criteria API 中的订单
【发布时间】:2016-04-08 20:13:04
【问题描述】:

我的实体看起来像:

 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

【问题讨论】:

标签: java jpa eclipselink criteria criteria-api


【解决方案1】:

这个怎么样?

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

【讨论】:

    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 2019-03-13
      • 2019-11-10
      • 2013-06-21
      • 2014-02-19
      • 1970-01-01
      • 2019-03-15
      • 2011-04-30
      • 2018-12-24
      相关资源
      最近更新 更多