I want to to implement pagination in spring application.I know using repository we can implement pagination but we can not write our own query for data retrieve there are li
I am providing a code snippet on how we implement pagination using springboot with jpa simply using PagingAndSortingRepository which contains inbuild method for pagination.
public interface PersonRepository extends PagingAndSortingRepository {
}
@Service
public class PersonServiceImpl implements PersonService{
@Autowired
private PersonRepository personRepository;
public Page listAll(int pageNumber){
if(pageNumber>0){
Pageable pageWithTenElements = PageRequest.of(pageNumber-1,10);
//first param decide page and second param decide no of record
return personRepository.findAll(pageWithTenElements);}
else
return null;
}
}
@RestController
public class AppController {
@Autowired
private PersonService personService;
@GetMapping("/page/{pageNumber}")
public ResponseEntity> getPersons(@PathVariable("pageNumber") pageNumber){
List persons = personService.listAll(pageNumber).getContent();
ResponseEntity response =
new ResponseEntity>(persons,HttpStatus.OK);
return response;
}
}