e-info128
e-info128

Reputation: 4072

Howto set limit result per page in jpa and PagingAndSortingRepository?

Have a Spring Boot Blog project, and need show the lastest favorites post in main page, in the database have a table with the posts and a column with boolean value (tinyint) show_in_main_page, it define if the post show in the main page or not.

In the java controller get dinamicaly widgets and the get the lastest favorites post by each widget, have a foreach with each widget but need get 1 or more post by each widget, i using PagingAndSortingRepository and Page<> results, in the while of controller call nextPageable() and next last favorite post.

Howto set the 1 result for each page in the repository? howto make a dinamicaly function with the number of results per page?, by example: call repository to get 3 results by page called from the controller when 3 is a dinamicaly value.

My interface is:

public interface PostRepository extends PagingAndSortingRepository<PostEntity, Long>{
    Page<PostEntity> findAll(Pageable pageable);
    Page<PostEntity> findByShowInMainPage(Boolean showInMainPage); // <--
}

Upvotes: 1

Views: 1170

Answers (2)

Lucas Holt
Lucas Holt

Reputation: 3826

If you're trying to get paging from the controller, just add a parameter on the control for Pageable. For example

@RequestMapping(value = "{username}", method = RequestMethod.GET, produces = MediaType.TEXT_HTML_VALUE)
    public String entries(@PathVariable(PATH_USERNAME) final String username,
                          final Pageable pageable,
                          final Model model) {
...

This will give you parameters automatically on your controller for page and size. So the URL would look like /users/myusername?page=1&size=3 and would return the first 3 results. Setting page = 2 would get you the next 3 results and so on.

You can then pass the pageable variable to your repository's findAll method to get the data.

Upvotes: 0

Cepr0
Cepr0

Reputation: 30329

If I understand you correctly you need PageRequest:

Page<PostEntity> postEntityPage = findAll(new PageRequest(0, 3));

It fetch first (0) page with three PostEntity in the page.

Upvotes: 3

Related Questions