How to correctly update a org.springframework.data.domain.Page's list?

I'm using Spring data JPA. I have a situation where my database identity is a surrogate key which returns three records, but I have implemented the equals method to reduce the collection down to two names. How to update the Page<Person> byName after filtering out / removing records from it at the service layer?

Example:

ID license Name 1 123456 Kim Kardashian 2 123456 Kim Kardashian West 3 123456 Kim Kardashian 

When searching I want to return two records. I have overridden the equals and hashcode method to define equality based on the, license and name attributes. I'm okay with it arbitrarily picking 1 or 3 to represent the 123456 Kim Kardashian record.

ID license Name 1 123456 Kim Kardashian 2 123456 Kim Kardashian West 

Code snippet of the repository returning the 3 records, and now at the service layer I would like to filter it down to the two records.

 Page<Person> byName = PersonRepository.findByName( name, pageable); //Now remove duplicates based on the equals() method rather than database identity (this is a read-only entity. List<Person> collect = byName.get().distinct().collect(Collectors.toList()); //how to place the replace the list back in the byName and the paging information is accurate? return ????; 

2 Answers

You can use this utility method

import org.springframework.data.domain.PageImpl; import org.springframework.data.domain.PageRequest; public static <T> Page<T> toPage(List<T> list, int pageNumber, int pageSize, int totalRecords) { PageRequest pageable = PageRequest.of(pageNumber, pageSize); return new PageImpl<>(list, pageable, totalRecords); } 

pageNumber starts from 0

The standard implementation of Page is immutable, so you have to create a new instance, either using PageImpl or . Note that your Page will be somewhat broken, because it doesn't contain the correct number of elements.

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

You Might Also Like