Map stream of Data into Page<T>
Asked Answered
M

2

14

For quite a while now I am trying to get following to work in my resource / controller:

Have a stream of data and then map the stream of data to a Page response

Page<SomeType> controllerMethod() {

    List<SomeType> allItems = someRepository.findAll()
                              .filter(something)
                              .collect(Collectors.toList())

    return allItems.map(...?)
}

Question:

Are there any helpers from spring that can help me acheive this?

It would be ok that the paging is not done on DB level.

Mule answered 22/10, 2018 at 13:14 Comment(5)
If you're using spring data repositories, you can make the return type Page<T> and it's automatically convertedBreeding
It would be ok that the paging is not done on DB level. Answer is no, paging should always be done at DB level for performance. Example, you have 1 million row and should you load all in one?Hove
How can you be sure that all your data will fit in one page ? If not, how will you server subsequent pages ? As others mentioned, Paging should be done at db level, and spring-data has support for that.Tempo
Sometimes you have complex queries that cannot be acheived with db queries alone.For example you have transient properties that calculate some "complicated stuff" with database data + configuration params from spring. Then you need to get the smallest subset you can from the db and then do some custom filter magic (based on transient props). The only question for me was : how to put it into a returning Page object.Mule
@Mule isn't this achievable with criteria api, which supports pagination?Rhetorician
G
34

PageImpl has constructor from list

Page<SomeType> controllerMethod() {

    List<SomeType> allItems = someRepository.findAll()
                              .filter(something)
                              .collect(Collectors.toList())

    return new PageImpl<>(allItems);
}
Guilbert answered 22/10, 2018 at 22:37 Comment(2)
Hi, Welcome to Stack Overflow. Please add some explanation to your answer so as to help future users.Romy
Thanks. Exactly what I was looking forMule
M
1

Using map(), you can convert to another object without converting to List.

public interface Page<T> extends Slice<T> {
...
<U> Page<U> map(Function<? super T, ? extends U> converter);
}

For example, If you want to convert Entity into Dto, you can use it like below.

Page<Entity> entities = aRepository.findAll(pageable);
Page<Dto> dtos = entities.map(entity -> {
    Dto.builder()
    ...
    .build();
  })
Merchant answered 1/2 at 10:35 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.