Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I am using spring boot with hibernate and I want to use pagination in my project. I have searched on google and saw many examples but I am unable to implement it in my project.

I want like if I pass 1 in my url then 10 results should come and if I pass 2 then next 10 results should come and so on.

Here is my my Dao

@Transactional
public interface PostDao extends CrudRepository<Post, Long>{

@Query(getAllPostsByRank)
List<Post> getAllPostsByRank();

final String getAllPostsByRank= "from Post order by value DESC";
}

Here is my Controller

@RequestMapping("/top")
    @ResponseBody 
     public List<Post> getAllPosts(HttpServletRequest req, HttpServletResponse res) throws ServletException {

List<Post> postobj = postDao.getAllPostsByRank();
return postobj;
}

And here is my url:

http://localhost:8888/v1.0/post/top/1

Please suggest.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
227 views
Welcome To Ask or Share your Answers For Others

1 Answer

I would consider using org.springframework.data.domain.Pageable directly into your controller. This object can then be passed to your JPA layer where it will handle the number of returned results and the size.

The great thing about using Pageable is that it returns a Page object which can be used on the front-end to form previous/next page logic.

By default this class uses url parameters 'page' and 'size'; hence page=0&size=10 will return the first 10 items.

Hence in your case the code could look something like:

@ResponseBody
@RequestMapping("/top/pages/")
public List<Post> getAllPosts(@PageableDefault(value=10, page=0) Pageable pageable) throws ServletException {
    Page page = postDao.findAll(pageable);
    return page.getContent();
}

Notice the annotation @PageableDefault is just to set up the defaults & it's not required.

In the front-end the next page call can be <a href="/top/pages?page=1">Next</a>; this will return a list of Posts from 11 to 20.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...