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 ????;
CodePudding user response:
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
CodePudding user response:
The standard implementation of Page
is immutable, so you have to create a new instance, either using PageImpl
or https://docs.spring.io/spring-data/commons/docs/current/api/org/springframework/data/repository/support/PageableExecutionUtils.html. Note that your Page
will be somewhat broken, because it doesn't contain the correct number of elements.