Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pagination in List Java Spring

I'm working on a Spring project where I have Tasks (id, name) and Assignments (task_id, name, ...). When I get the tasks I also get assigned task, but I was not able to implement a pagination system.

public List<Tasks> getAllTasks() {
       List<Tasks> task = (List<Tasks>) taskRepository.findAll();
       return task;
   }

That's my current code. I want to display 10 items in each paginated side.

I tried something like that:

   public Page<Tasks> getAllTasks(Long page, Long size){
       List<Tasks> tsk = (List<Tasks>) taskRepository.findAll();
     
       int start =  new PageRequest(page, size).getOffset();
       int end = (start + new PageRequest(page, size).getPageSize()) > tsk.size() ? tsk.size() : (start + new PageRequest(page, size).getPageSize());

       return new PageImpl<Tasks>(tsk.subList(start, end), new PageRequest(page, size), tsk.size());
   }

but it's not working.

My current JSON response is as follows:

{
   id: 1,
   name: First Task
   assignments: [ 
        {
          id: 1,
          assignment_name: firstassignment
        },
        {
          id: 2,
          assignment_name: secondassignment
        }]
}

I also read that it doesn't need to be a List. I'm open for any ideas.

like image 694
Rosina Avatar asked Sep 16 '25 15:09

Rosina


1 Answers

You can create and send pageable as a parameter in findAll to get the data

public Page<Tasks> getAllTasks(int page, int size){
    Pageable pageable = PageRequest.of(page, size);
    return taskRepository.findAll(pageable);
}

A good article about Pagination in Spring Data JPA here

like image 71
Eklavya Avatar answered Sep 19 '25 06:09

Eklavya