如何按日期对查询结果进行排序(Jpa、Java Collections)
public List<Movie> findRange(int[] range) {
CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
cq.select(cq.from(Movie.class));
Query q = em.createQuery(cq);
q.setMaxResults(range[1] - range[0]);
q.setFirstResult(range[0]);
List<Movie> list1 = q.getResultList();
Collections.sort(list1, new Comparator(){
public int compare (Object o1, Object o2){
Movie p1 = (Movie)o1;
Movie p2 = (Movie)o2;
return p2.getDate().compareTo(p1.getDate());
}
});
return list1;
}
因为现在可以进行排序,但只能在批次中进行,
(批次 = 4 部电影)第一个 = 最后输入的;最后一个 = 第一个输入。
但仅与批次相比,并非全部符合要求。
非常感谢您提供的任何帮助
最好的问候
伊格纳西奥
public List<Movie> findRange(int[] range) {
CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
cq.select(cq.from(Movie.class));
Query q = em.createQuery(cq);
q.setMaxResults(range[1] - range[0]);
q.setFirstResult(range[0]);
List<Movie> list1 = q.getResultList();
Collections.sort(list1, new Comparator(){
public int compare (Object o1, Object o2){
Movie p1 = (Movie)o1;
Movie p2 = (Movie)o2;
return p2.getDate().compareTo(p1.getDate());
}
});
return list1;
}
As it is now sorting works, but only with in the batch,
(batch = 4 movies) First one = last entered; Last one = fisrt entered.
But only compared with those in the batch not all of them as needed.
Thank you very much for any help you can provide
best Regards
Ignacio
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可能应该在条件查询中定义顺序,而不是在执行查询后对结果进行排序。否则,您最终将仅对结果的一部分进行排序。
您可以使用 CriteriaQuery.orderBy(订单...)。可以使用 CriteriaBuilder 使用 asc(Expression) 用于升序或 desc(Expression) 用于降序排列。
以下内容可能有效,也可能无效:
You should probably define the order in the criteria query and not sort the results after the query has already been executed. Otherwise you will end up sorting only a part of the results.
You can assign sort order to the query using CriteriaQuery.orderBy(Order ...). The order by expression can be created with the CriteriaBuilder using either asc(Expression) for ascending or desc(Expression) for descending order.
The following might or might not work: