Spring Custom Query with pageable

前端 未结 6 750
自闭症患者
自闭症患者 2020-12-30 07:29

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

6条回答
  •  离开以前
    2020-12-30 08:16

    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;
       }
    
      }
    

提交回复
热议问题