【问题标题】:How to determine the page number of a record using Spring-data-jpa?如何使用 Spring-data-jpa 确定记录的页码?
【发布时间】:2020-08-24 18:37:20
【问题描述】:

我想返回某条记录所在页面的页码。我使用条件查询返回所有的分页结果,所以我无法根据记录的id确定它所在的页面。我该如何解决这个问题?

我在网上搜索了很长时间。但是没有用。请帮助或尝试提供一些想法如何实现这一目标。

我的临时解决方案是查询每个页面的记录,直到它包含我需要的记录,但是这样做会导致查询变慢。

ps:我使用的是 MySQL 数据库。

【问题讨论】:

  • 什么是“我使用条件查询返回所有的分页结果,所以我无法根据记录的id确定它所在的页面。”意思是?你是从Pageable 开始的吗?还是需要任意记录的页面?

标签: mysql sql spring-boot spring-data-jpa pageable


【解决方案1】:

假设您有一条带有某种 id 的记录,并且当表格按某些标准排序时,您可以知道它出现在表格中的什么位置,您可以使用分析函数来做到这一点。在给定页面大小的情况下,您可以根据该值轻松计算它出现的页面。

示例架构 (MySQL v8.0)

create table example (
  id integer not null primary key,
  text varchar(20));

insert into example(id, text) values (23,"Alfred");
insert into example(id, text) values (47,"Berta");
insert into example(id, text) values (11,"Carl");
insert into example(id, text) values (42,"Diana");
insert into example(id, text) values (17,"Ephraim");
insert into example(id, text) values (1,"Fiona");
insert into example(id, text) values (3,"Gerald");

查询

select * 
from (
    select id, text, 
        count(*) over (order by text) cnt // change the order by according to your needs 
    from example
    // a where clause here limits the table before counting
) x where id = 42; // this where clause finds the row you are interested in
| id  | text  | cnt |
| --- | ----- | --- |
| 42  | Diana | 4   |

为了将它与 Spring Data JPA 一起使用,您将此查询放在 @Query 注释中并将其标记为本机查询。

【讨论】:

    猜你喜欢
    • 2017-06-20
    • 2017-01-13
    • 2016-12-07
    • 2019-06-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-10
    • 2018-02-26
    相关资源
    最近更新 更多