如何使用 Spring-data-jpa 确定记录的页码?

How to determine the page number of a record using Spring-data-jpa?

我要return某条记录所在页码。我用条件查询return所有的分页结果,所以无法根据记录的id来判断所在的页面。我该如何解决这个问题?

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

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

ps: 我正在使用 MySQL 数据库。

假设你有一个带有某种 id 的记录,当 table 按某些标准排序时,你可以知道它出现在你的 table 中的什么位置,你可以使用分析函数来做到这一点.根据这个值,您可以根据页面大小简单地计算出它出现在哪个页面上。

示例架构 (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 注释中并将其标记为本机查询。