Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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)?

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading