728x90
pagination을 사용해서 조회한 Entity 정보를 API의 응답으로 제공할 때, 의외로 잘 모르시는 부분이 있습니다.
Entity를 API의 응답으로 그대로 노출하면 안되기 때문에 아래와 같이 변환하시는 경우가 있습니다.
Page<Member> memberList = memberJpaRepository.findPageByName("name", PageRequest.of(0, 10));
List<MemberReadResponse> memberDto = memberList.getContent()
.stream()
.map(m -> new MemberReadResponse(m.getId(), m.getName()))
.collect(Collectors.toList());
response = new MemberResponseDto(memberDto, memberList.getPageable())
이럴 때에는 page에서 제공하는 map 메서드를 사용하면 쉽게 변환할 수 있습니다.\
public interface Page<T> extends Slice<T> {
/**
* Returns a new {@link Page} with the content of the current one mapped by the given {@link Function}.
*
* @param converter must not be {@literal null}.
* @return a new {@link Page} with the content of the current one mapped by the given {@link Function}.
* @since 1.10
*/
<U> Page<U> map(Function<? super T, ? extends U> converter);
}
Page<MemberReadResponse> memberDto = memberList
.map(m -> new MemberReadResponse(m.getId(), m.getName()));
728x90
'DEV > Spring Data JPA' 카테고리의 다른 글
@EntityGraph로 fetch join 쉽게 쓰기 (0) | 2023.09.24 |
---|---|
Update 쿼리를 호출할 때 주의사항 2가지 (0) | 2023.09.24 |
Join과 Pagination 함께 사용할 때 Count 쿼리 최적화 (0) | 2023.09.24 |
COUNT 쿼리, Page<T> vs Slice<T> (0) | 2023.09.24 |
데이터 조회의 반환값 T vs Optional<T> (0) | 2023.09.24 |