Implement pagination with Spring MVC and Hibernate

I am trying to implement pagination using Spring MVC and Hibernate.

Here is my DAO layer:

private static final int LIMITITEMSPERPAGE = 6;

public List<Video> listVideosByKids(int page) {

    Query query = sessionFactory.getCurrentSession().createQuery("from Video where type=1");
    query.setMaxResults(LIMITITEMSPERPAGE);
    query.setFirstResult(page * LIMITITEMSPERPAGE);

    return (List<Video>) query.list();

}

Here is my controller:

@RequestMapping("/list")
    public String listKids(@RequestParam(value = "page") int page, ModelMap model) {
        model.addAttribute("listVideos", videoService.listVideosByKids(page));
        return "/kids/list";
    }

When I go to the URL, for example:

http://localhost:8080/kids/list/?page=0

I get the first 6 items from the database and everything works fine. But I would like to get the first 6 elements without getting the page URL in the URL , simply:

http://localhost:8080/kids/list/

But if I open url:

http://localhost:8080/kids/list/?page=1 

then i get the second 6 items.

Any ideas?

+4
source share
1 answer

When clicked, http://localhost:8080/kids/list/the page setting is missing . You can add a default value to it with a required value of false.

@RequestMapping("/list")
    public String listKids(@RequestParam(value = "page", defaultValue="0", required=false) int page, ModelMap model) {
        model.addAttribute("listVideos", videoService.listVideosByKids(page));
        return "/kids/list";
    }
+2

Source: https://habr.com/ru/post/1547310/


All Articles