pagination in java?

前端 未结 4 447
孤街浪徒
孤街浪徒 2021-01-03 10:12

i want the numbers to be displayed in this format..

1 2 3 4 5 ^
where if i press 5, then it should display from 5 to 10

5 6 7 8 9 10

til

4条回答
  •  情话喂你
    2021-01-03 10:47

    Normally you want your database to do the heavy lifting for pagination and sorting. With MySQL for example you can get a page of results sorted by date by adding

    ORDER BY date ASC LIMIT 5,5
    

    to the end of your SQL query. If you use hibernate you can do this in a vendor-independent way using the criteria API:

    List results = (List) getSession()     
    .createCriteria(MyDomainClass.class)
    .setFirstResult(5)
    .setMaxResults(5)
    .addOrder(Order.asc("date"))
    .list();
    

    To display a pagination navigation you also need to count the total number of results to know how many pages there are:

    int count = (int) getSession()     
    .createCriteria(MyDomainClass.class)
    .setProjection(Projections.rowCount())
    .list().get(0);
    

    You can add restrictions to both searches, for example when you want to filter on lastname you could add:

    .add(Restrictions.eq("lastname", "Smith")
    

    (This needs to be added to both the count query and the list query).

    When you know the total number of results, the pagesize and the current page number you can calculate the range of results like this :

    // TODO: execute the count query here to determine totalResults
    int totalPages = Math.ceil(totalResults / pageSize);
    // show first page by default
    int firstResult = 0;
    if (currentPage >= 0 && currentPage < totalPages) {
        firstResult = currentPage * pageSize;    
    }
    // the number of items might be less than the page size (i.e. on the last page)
    int count = Math.min(pageSize, totalResults - firstResult);        
    // TODO: execute the list query here to get a page of data
    

    How you display the navigation is up to you. Some frameworks have standard components for that. Otherwise you will have to think of a way to handle huge amounts of pages. A common approach is to show a range of say 10 page numbers and forward/backward jump to start/jump to end links.

    Hope this helps.

提交回复
热议问题