기존의 나는 DTO를 이용하긴 했으나, 배열로 나온다는 문제점이 있었다.
기존 코드
@Override
@Transactional(readOnly = true)
public ResponseEntity getProductList(int page, int size){
Pageable pageable = PageRequest.of(page-1, size);
Page<Product> products = productRepository.findAll(pageable);
List<ProductResponse> productReponseDtoList = products.stream()
.map(product -> new ProductResponse(product)).collect(Collectors.toList());
return new ResponseEntity<>(productReponseDtoList, HttpStatus.OK);
}
결과는??
[
{
"productId": 1,
"productName": "macbook",
"productPrice": 20000,
"quantity": 50,
"productImage": "www.naver.com",
"productDetail": "Macbook is good",
"productCategory": 1
},
{
"productId": 2,
"productName": "mac",
"productPrice": 30000,
"quantity": 1,
"productImage": "www.google.com",
"productDetail": "Mac is good",
"productCategory": 1
},
{
"productId": 3,
"productName": "iPhone",
"productPrice": 40000,
"quantity": 50,
"productImage": "www.daum.net",
"productDetail": "iPhone is good",
"productCategory": 2
}
]
이렇게 배열에 담겨 나왔다.
배열은 크기와 순서가 정해져 있기 때문에, 변경사항에 대한 유연함을 확보할 수 없다는 문제가 있다.
변경
그래서
Result.java
import lombok.AllArgsConstructor;
import lombok.Data;
@Data
@AllArgsConstructor
public class Result<T> {
private T data;
}
제네릭 클래스를 하나 만들고,
@Override
@Transactional(readOnly = true)
public Result getProductList(int page, int size){
Pageable pageable = PageRequest.of(page-1, size);
Page<Product> products = productRepository.findAll(pageable);
List<ProductResponse> productReponseDtoList = products.stream()
.map(product -> new ProductResponse(product)).collect(Collectors.toList());
return new Result(productReponseDtoList);
}
리턴 타입으로 이 클래스를 반환하도록 만들었다.
그리고 그 결과는?
{
"data": [
{
"productId": 1,
"productName": "macbook",
"productPrice": 20000,
"quantity": 50,
"productImage": "www.naver.com",
"productDetail": "Macbook is good",
"productCategory": 1
},
{
"productId": 2,
"productName": "mac",
"productPrice": 30000,
"quantity": 1,
"productImage": "www.google.com",
"productDetail": "Mac is good",
"productCategory": 1
},
{
"productId": 3,
"productName": "iPhone",
"productPrice": 40000,
"quantity": 50,
"productImage": "www.daum.net",
"productDetail": "iPhone is good",
"productCategory": 2
}
]
}
기존의 전체를 감싸고 있던 배열은 data라는 일부를 감싸는 배열이 되었다.
이로써 유연성을 확보할 수 있게 되었다.
잘 써먹어보자!
'개발일지 > 일간회고 (TIL)' 카테고리의 다른 글
devtools에 대해 (0) | 2023.02.04 |
---|---|
정적, 동적 메서드란? (0) | 2023.02.04 |
테스트 코드 문제상황 발생!! (0) | 2023.01.26 |
PasswordEncoder 비밀번호 비교 이슈 (0) | 2023.01.24 |
orElseThrow 메소드 (0) | 2023.01.21 |