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

问题描述 投票:0回答:1

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

我在网上搜索了很久。但是没有用。请大家帮忙或试着给一些想法,如何实现。

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

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

mysql sql spring-boot spring-data-jpa pageable
1个回答
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 注解并将其标记为本地查询。

© www.soinside.com 2019 - 2024. All rights reserved.