Home > Mobile >  How to map from Page<ObjectOne> to Page<ObjectTwo> in Spring Data 2?
How to map from Page<ObjectOne> to Page<ObjectTwo> in Spring Data 2?

Time:04-07

I'm looking at some old code and I'm trying to re-write it however I encountered a problem.

This is the old code that works perfectly fine:

public Page<SearchResult> search(String text, int pageNumber) {
    
    PageRequest request = PageRequest.of(pageNumber-1, itemsPerPage);
    Page<Profile> results = profileDao.findByInterestsNameContainingIgnoreCase(text, request);
    
    Converter<Profile, SearchResult> converter = new Converter<Profile, SearchResult>() {
        @Override
        public SearchResult convert(Profile profile) {
            return new SearchResult(profile);
        }       
    };
    
    return results.map(converter);
}

But I'm using Spring Data 2, where the Page map method takes a Function instead of a Converter so I don't know how to re-write this.

I read this topic: How to map Page<ObjectEntity> to Page<ObjectDTO> in spring-data-rest but I failed to convert Page<Profile> into Page<SearchResult> because I still don't fully understand this Function concept.

Could someone translate code snippet from above using Spring Data 2 method (Function instead of a Converter)?

CodePudding user response:

Based on your example I would implement the map function as follows:

Page<SearchResult> searchResultPage = results.map(profile -> new SearchResult(profile));

If you are interested in a short introduction to lambda expressions and functional interfaces I recommend checking out the following summary: https://www.baeldung.com/java-8-lambda-expressions-tips

  • Related