Smajl Smajl - 1 month ago 24
Java Question

Spring Boot JPA - paging and sorting

I am trying to implement pagination to my Spring Data JPA repository in Spring Boot but I am stuck with the following exception when running uni tests:

org.springframework.web.util.NestedServletException: Request processing failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.data.domain.Pageable]: Specified class is an interface
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:982)
...


Could someone point out to me what am I missing here? This is my repository:

@Repository
public interface VenueRepository extends PagingAndSortingRepository<Venue, Long> {

public Page<Venue> findAll(Pageable pageable);

}


and controller:

@RestController
@RequestMapping("/venues")
public class VenueController {

@Autowired
private VenueRepository venueRepo;

@RequestMapping(method = RequestMethod.GET)
public ResponseEntity<Page<Venue>> getVenues(Pageable pageable) {
return new ResponseEntity<>(venueRepo.findAll(pageable), HttpStatus.OK);
}
}


and finally my test:

@Test
public void responseOkVenuesTest() throws Exception {
mvc.perform(get("/venues").accept(MediaType.APPLICATION_JSON_VALUE)).andExpect(status().isOk());
}


I spent couple of hours trying to make this work and am running out of ideas. Thank you for any tips!

Answer

Change your method getVenues in the way that you can pass the parameters to instantiate a PageRequest instead of passing Pageable :

 @RequestMapping(method = RequestMethod.GET)
  public ResponseEntity<List<Venue>> getVenues(int from,int to) {
     return new ResponseEntity<>(
        venueRepo.findAll((new PageRequest(from, to)), HttpStatus.OK).getContent();
  }