[JPA2] API개발과 고급-DTO 직접조회-플랫데이터 최적화(6)

레몬커드요거트·2022년 11월 10일
0

V6:JPA에서 DTO로 직접 조회- 플랫데이터 최적화

public List<OrderFlatDto> findAllByDto_flat() {
  return em.createQuery(
    "select new jpabook.jpashop.repository.order.query.OrderFlatDto(o.id, m.name, o.orderDate, o.status, d.address, i.name, oi.orderPrice, oi.count)" +
    " from Order o" +
    " join o.member m" +
    " join o.delivery d" +
    " join o.orderItems oi" +
    " join oi.item i", OrderFlatDto.class)
    .getResultList();
}
    @GetMapping("/api/v6/orders")
    public List<OrderFlatDto> ordersV6(){
        return orderQueryRepository.findAllByDto_flat();
    }
package jpabook.jpashop.repository.order.query;

import jpabook.jpashop.domain.Address;
import jpabook.jpashop.domain.OrderStatus;
import lombok.Data;

import java.time.LocalDateTime;

@Data
public class OrderFlatDto {
    //order,orderitem 한번에 조인 -> SQL에 한 줄로 가져옴
    private Long orderId;
    private String name;
    private LocalDateTime orderDate;
    private OrderStatus orderStatus;
    private Address address;

    private String itemName;
    private int orderPrice;
    private int count;

    public OrderFlatDto(Long orderId, String name, LocalDateTime orderDate, OrderStatus orderStatus, Address address, String itemName, int orderPrice, int count) {
        this.orderId = orderId;
        this.name = name;
        this.orderDate = orderDate;
        this.orderStatus = orderStatus;
        this.address = address;
        this.itemName = itemName;
        this.orderPrice = orderPrice;
        this.count = count;
    }
}


📍중복제거

@GetMapping("/api/v6/orders")
public List<OrderQueryDto> ordersV6(){
  //return orderQueryRepository.findAllByDto_flat();

  List<OrderFlatDto> flats = orderQueryRepository.findAllByDto_flat();

  return flats.stream()
    .collect(groupingBy(o -> new OrderQueryDto(o.getOrderId(), o.getName(), o.getOrderDate(), o.getOrderStatus(), o.getAddress()),
                        mapping(o -> new OrderItemQueryDto(o.getOrderId(), o.getItemName(), o.getOrderPrice(), o.getCount()), toList())
                       )).entrySet().stream()
    .map(e -> new OrderQueryDto(e.getKey().getOrderId(), e.getKey().getName(), e.getKey().getOrderDate(), e.getKey().getOrderStatus(), e.getKey().getAddress(), e.getValue()))
    .collect(toList());
}
public OrderQueryDto(Long orderId, String name, LocalDateTime orderDate, OrderStatus orderStatus, Address address, List<OrderItemQueryDto> orderItems) {
  this.orderId = orderId;
  this.name = name;
  this.orderDate = orderDate;
  this.orderStatus = orderStatus;
  this.address = address;
  this.orderItems = orderItems;
}

쿼리가 1번 날아온다는 장점이 존재하지만,
조인으로인해 DB에서 중복데이터가 추가되므로 V5보다 느릴 수도 있다.

페이징 역시 불가능.

profile
비요뜨 최고~

0개의 댓글