NHN toast-grid 연동 JPA pageable custom 하기
2023. 2. 28. 18:00ㆍJPA
토스트 페이지네이션 같은 경우
{
"result": true, //성공, 실패
"data": {
"contents": [], // 실제 데이터
"pagination": { //페이징 관련
"page": 1, //페이지
"totalCount": 100 //데이터 개수
}
}
}
이 형식으로 json 응답을 내려줘야 작동을 하게 된다.
그러기에 객체를 생성해줬다.
@Getter
@Builder
public class GridData {
private List<?> contents;
private Pagination pagination;
}
@Getter
@Setter
public class Pagination {
@Builder
public Pagination(Integer page, Integer totalCount, Integer perPage) {
this.page = page;
this.totalCount = totalCount;
this.perPage = perPage;
}
private Integer page;
private Integer totalCount;
private Integer perPage;
}
@Getter
public class GridResult {
private boolean result;
private GridData data;
public GridResult(List<?> contents, Pagination pagination) {
this.result = true;
this.data = GridData.builder()
.contents(contents)
.pagination(Pagination.builder()
.page(pagination.getPage())
.totalCount(pagination.getTotalCount())
.perPage(pagination.getPerPage())
.build()
)
.build();
}
}
이렇게 만들어주는 맨 위의 양식에 paging 처리가 완성이 된다.
toast 같은 경우 페이지에서 perPage와 page를 항상 물고다니며 서버에 넘겨준다.
jpa Pageable를 사용해야 할 경우 toast에서 첫번째 페이지는 1이지만 pageable에선 0이므로 맞춰줘야 하며
화면에 보여줄 페이지 수 같은 경우에도 toast는 perPage pageable은 size로 다르기 때문에 pageable을 커스텀 하기로
마음을 먹었다.
@Configuration
public class CustomPageableConfiguration {
@Bean
public PageableHandlerMethodArgumentResolverCustomizer customize() {
return p -> {
p.setSizeParameterName("perPage");
p.setOneIndexedParameters(true);
p.setMaxPageSize(2000);
};
}
}
Pageable 구현체가 Bean으로 등록되기전에 위의 빈을 생성하게 되면 앞쪽에 bean은 생성되지 않고 위에 bean을 사용하게 된다. 이것을 지정할 수 있는 곳은 yml, @PageDefault 가 있는데
spring:
data:
web:
pageable:
default-page-size: 10
max-page-size: 2000
@PageableDefault(size=10)
우선 순위 같은경우는 3이 있을경우 3-2-1, 3이 없으면 1-2 순서가 된다.
위와 같이 size 파라미터 이름을 perPage로 변경하였고 페이지 시작도 1이 되도록 변경하였다.
controller에서는
@GetMapping("/hongs")
public GridResult findAllByNameContaining( Pageable pageable, Integer page, Integer perPage) {
Page<HongUser> list = hongRepository.findAll(pageable);
log.info("list: {}", list);
Pagination pagination = Pagination.builder()
.page(page)
.totalCount((int) list.getTotalElements())
.perPage(perPage)
.build();
return new GridResult(list.getContent(), pagination);
}
이런식으로 클라이언트에서 받아온 page와 perPage를 넘겨 다시 응답해주면 완성이다.