작성
·
329
1
Address 필드가 Response 시 빈 객체로 나옵니다.
log를 찍어 봤는데 아래와 같이 dto에 address는 잘 들어가있습니다.
2022-06-26 00:43:11.618 INFO 4953 --- [nio-8080-exec-2] j.jpashop.api.OrderSimpleApiController : dto address = Address(city=서울, street=1, zipcode=1111)
2022-06-26 00:43:11.618 INFO 4953 --- [nio-8080-exec-2] j.jpashop.api.OrderSimpleApiController : dto address = Address(city=진주, street=2, zipcode=2222)
뭐가 문제일까요 ㅠㅠㅠ
전체코드
package jpabook.jpashop.api;
import jpabook.jpashop.domain.entity.Address;
import jpabook.jpashop.domain.entity.Order;
import jpabook.jpashop.domain.entity.OrderStatus;
import jpabook.jpashop.domain.repository.OrderRepository;
import jpabook.jpashop.domain.repository.OrderSearch;
import lombok.Data;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;
/**
* xToOne(ManyToOne, OneToOne)
* Order
* Order -> Member
* Order -> Delivery
*/
@Slf4j
@RestController
@RequiredArgsConstructor
public class OrderSimpleApiController {
private final OrderRepository orderRepository;
@GetMapping("/api/v1/simple-orders")
public List<Order> ordersV1() {
List<Order> all = orderRepository.findAllByString(new OrderSearch());
all.stream().forEach(o -> {
o.getMember().getName(); // Lazy 강제 초기화
o.getDelivery().getAddress(); // Lazy 강제 초기화
});
return all;
}
@GetMapping("/api/v2/simple-orders")
public List<SimpleOrderDto> ordersV2() {
List<Order> orders = orderRepository.findAllByString(new OrderSearch());
List<SimpleOrderDto> result = orders.stream()
.map(SimpleOrderDto::new)
.collect(Collectors.toList());
result.forEach(dto -> log.info("dto address = {}", dto.getAddress()));
return result;
}
@Data
static class SimpleOrderDto {
private Long orderId;
private String name;
private LocalDateTime orderDate;
private OrderStatus orderStatus;
private Address address;
public SimpleOrderDto(Order order) {
orderId = order.getId();
name = order.getMember().getName();
orderDate = order.getOrderDate();
orderStatus = order.getStatus();
address = order.getDelivery().getAddress();
}
}
}