Search code examples
javaangularhibernatespring-bootjpa

How can I choose ideal way for pagination in Spring boot?


I need your advice for paginations.

My table data is very long.Therefor I use pagination and every pag action İ call data from database
I have a rest method in spring-boot application.
This method could get data from database and everthing is ok.
I need pag count(all count of my data/ perPage count).
I can find this count from db.
I must write two seperate method for allCount and the below method?

How can I use ideal way for pagination in Spring boot?

  @CrossOrigin(maxAge = 3600)
    @RequestMapping(value = "/payment/all", method = RequestMethod.POST)
    public List<NotaryPaymentInformationEntity> getAllProduct(@RequestBody PaginationModel pag){
        try {
            System.out.println(pag.getPageno()+ " " + pag.getRecords());
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        Pageable pageable = new PageRequest(pag.getPageno(), pag.getRecords());
        System.out.println("here"+notaryPaymentRepository.findAll(pageable).getContent().size());
        return notaryPaymentRepository.findAll(pageable).getContent();
    }




public interface NotaryPaymentRepository  extends JpaRepository<NotaryPaymentInformationEntity,Integer>{


}

enter image description here


Solution

  • You can get the response of your query in Page class obj which extends the Slice class and has all the methods you would need.

    Pageable pageable = new PageRequest(pageNo, PAGE_SIZE);
    

    The pageNo and PAGE_SIZE needs to be sent from the client

    @Query(value = "SELECT h FROM {NameOfYourModelClass} h")
    Page<HorseWatch> getPaginatedModel(Pageable pageable);
    

    Call this method from your service class and retrieve it in a Page object

    You can get the page content, page number and total number of pages using (using getContent(),getNumber(),getTotalPages() from the object )

    Save these values in your response class and send this class back to the client

    public class PageResponse {
        private List<{NameOfModelClass}> content;
        private int currentPage;
        private int totalPages;
    }