在 Spring Data JPA 中创建分页 [英] Creating Pagination in Spring Data JPA

查看:32
本文介绍了在 Spring Data JPA 中创建分页的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在 Spring Data JPA 中实现分页功能.我引用这个博客我的控制器包含以下代码:

I am trying to implement pagination feature in Spring Data JPA. I am referring this Blog My Controller contains following code :

 @RequestMapping(value="/organizationData", method = RequestMethod.GET)
  public String list(Pageable pageable, Model model){
    Page<Organization> members = this.OrganizationRepository.findAll(pageable);
    model.addAttribute("members", members.getContent());
    float nrOfPages = members.getTotalPages();
    model.addAttribute("maxPages", nrOfPages);
    return "members/list"; 
  }

我的 DAO 如下:

@Query(value="select m from Member m", countQuery="select count(m) from Member m")
  Page<Organization> findMembers(Pageable pageable);

我可以显示前 20 条记录,如何显示接下来的 20 条???有没有其他分页示例可以参考?

I am able to show first 20 records, how do I show next 20??? Is there any other pagination example that I can refer??

推荐答案

我上周看到过类似的问题,但是找不到所以直接回答.

I've seen similar problem last week, but can't find it so I'll answer directly.

你的问题是你指定参数太晚了.Pageable 的工作方式如下:您创建具有某些属性的 Pageable 对象.您至少可以指定:

Your problem is that you specify the parameters too late. Pageable works the following way: you create Pageable object with certain properties. You can at least specify:

  1. 页面大小,
  2. 页码,
  3. 排序.

所以让我们假设我们有:

So let's assume that we have:

PageRequest p = new PageRequest(2, 20);

以上传递给查询的内容将过滤结果,因此只会返回第 21 至 40 日的结果.

the above passed to the query will filter the results so only results from 21th to 40th will be returned.

您不对结果应用 Pageable.你通过查询传递它.

You don't apply Pageable on result. You pass it with the query.

不推荐使用 PageRequest 的构造函数.使用 Pageable pageable = PageRequest.of(2, 20);

Constructors of PageRequest are deprecated. Use Pageable pageable = PageRequest.of(2, 20);

这篇关于在 Spring Data JPA 中创建分页的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆