Search code examples
javahibernatepaginationspring-boothql

How to implement pagination in spring boot with hibernate


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.


Solution

  • Check it. Your controller

    @RequestMapping("/top/pages/{pageno}")
        @ResponseBody 
         public List<Post> getAllPosts(@PathVariable("pageno") int pageno, HttpServletRequest req, HttpServletResponse res) throws ServletException {
    
    List<Post> postobj = postDao.getAllPostsByRank(new PageRequest(pageno,10));
    return postobj;
    }
    

    Your dao

    @Transactional
    public interface PostDao extends CrudRepository<Post, Long>{
    
    @Query(getAllPostsByRank)
    List<Post> getAllPostsByRank(Pageable pageable);
    
    final String getAllPostsByRank= "from Post order by value DESC";
    }