r/SpringBoot • • Sep 13 '26

Question Pagination in Springboot

If you're ar working on springboot project in you company/job. How does your team do pagination in your project as they have large datasets. I am currently learning springboot and curious to know how it's done withel large datasets.

55 Upvotes

33 comments sorted by

View all comments

50

u/wimdeblauwe Sep 13 '26

A RestController method can accept a Pageable argument and return a Page<T>. Combine it with a PagingAndSortingRepository of Spring Data JPA.

17

u/Just_LeonS Sep 13 '26

Works terribly on big datasets.

7

u/guss_bro Sep 13 '26

If count query is slow, return List<T> instead of Page .

We use it for giant db. No issues.

You can also use Slice

3

u/j-an Sep 13 '26

Can you give your rough estimate at what point a data set is considered large?

How I see it you can use a List/slice, if you don't need to know the total size of your data set. Do you need to go over the entire dataset anyways, as soon as you have some filtering with it? I guess a good index would be the first thing to improve the query.

2

u/Just_LeonS Sep 13 '26

My source (enable subtitles, I guess)

postgres:

slice:

~800 ms per page for ordered query ~1000th page of very plain three-simple-fields-entity.

~50 ms for unordered slice

~20 ms constant-ish for ordered keyset pagination for any of 1 ~ 9000 pages

1

u/analcocoacream Sep 13 '26

Also, it counts the total numberf of rows,

0

u/kamen1991 Sep 13 '26 edited Sep 13 '26

And you expose your whole database entities schema. :) The first thing to do is to decouple the spring based classes, they're implementation details. Returning DTOs from the controller is an absolute requirement. For parameters use query params, page, size, sort etc. and then you can map them to Spring page, Specification, Query params or whatever is your implementation. That way you can refactor your codebase without breaking any of your clients, you can even replace your database with redis or whatever you want if the business decides they want to move away from relational database.

9

u/wimdeblauwe Sep 13 '26

I never said that T was an entity. It should indeed be a DTO in the controller. Page has a map() method to map the entity from the service/repository to a DTO.