2016-04-05 59 views
0

我的實體的樣子:秩序JPA標準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)如何在條件中添加TagstagsListAuthor

+0

集合的大小是通過CriteriaBuilder.size完成的(......)與參數是「from.get(」commentsList「)」。試過了嗎? –

+0

[構建JPA Criteria API查詢 - 按集合中元素的數量進行排序]的可能重複(http://stackoverflow.com/questions/21005794/building-jpa-criteria-api-query-sorting-by-number-of- elements-in-collection) – riskop

回答

1

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

這是怎麼回事?

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

謝謝。它解決了一些問題 – Nox