3

I have an application which shows some comments. Now I want to sort the comments by create time asc, but I want to show the latest comments as default.

I do it like this:

public Page<Comment> getComments(@PageableDefault(value = 15, sort = { "createdTime" }, direction = Sort.Direction.ASC) 
    Pageable pageable) {
    return commentRepository.findAll(pageable);
 }

Now I can only get the first page as default, what shall I do to get the last page as default?

Wandering Fool
  • 2,170
  • 3
  • 18
  • 48
xierui
  • 1,047
  • 1
  • 9
  • 22
  • And, why can't you sort descending and take the first page? – manish Aug 15 '15 at 14:21
  • Because we want comment sort by createdTime asc. At most of time, we read the comments from the first to the last, and some times we want to see the last page directly – xierui Aug 18 '15 at 04:01
  • Then, pass the sort order to the method as well. With your accepted answer you are running two separate queries, whereas you can do with just one query if you sort descending and take the first page. – manish Aug 18 '15 at 05:18
  • If I have 15 comments total and the page size is 10. The first page size is 10 and the last page size is 5. If I just sort descending and take the first page I will get the last page.which have 10 comments. obviously I do not want that. – xierui Aug 19 '15 at 11:19

2 Answers2

0

1.Set first and max result for a page.

setFirstResult(int first) ;
setMaxResults(int max) ;

2.Count total number of pages you have for that table and divide by page size.

Query query=em.createQuery("SELECT COUNT
(emp.empName) FROM Employee emp");

or another one is to use a projection

criteria.setProjection(Projections.rowCount());
int rowCount = (Integer) criteria.list().get(0);

3.Move to the last page.

Client Side sorting + Hibernate Paging?

reference: Spring Data JPA, how to get the last Page through Pageable

VGR
  • 40,506
  • 4
  • 48
  • 63
Piyush Mittal
  • 1,860
  • 1
  • 21
  • 39
  • There are many objects want to do that, like discussions tutorials and something others. Is there any common way to fix it? – xierui Aug 14 '15 at 08:07
0

A simpler alternative would simply be to reverse the order of the query (changing your 'order by' clause) and simply return the first page of results. This approach may also be more efficient assuming that you have an index in place to support the sort-order.

Tom Drake
  • 527
  • 5
  • 11