[英]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)如何从tagsList
和Author
中添加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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.