How to sort a query result by their date (Jpa, Java Collections)
public List<Movie> findRange(int[] range) {
CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
cq.select(cq.from(Movie.class));
Query q = em.createQ开发者_C百科uery(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 IgnacioYou 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:
public List<Movie> findRange(int[] range) {
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<Movie> cq = cb.createQuery(Movie.class);
Root<Movie> movie = cq.from(Movie.class);
cq.select(movie);
cq.order(cb.asc(movie.get(Movie_.getDate()));
...
}
精彩评论