Skip to content

Commit

Permalink
Merge pull request #2 from pushedrumex/refactor
Browse files Browse the repository at this point in the history
refactor: 주문 상품 반정규화 및 상품 통계 테이블 생성
  • Loading branch information
pushedrumex authored Apr 18, 2024
2 parents eecf23f + 7d54ce5 commit 23652e4
Show file tree
Hide file tree
Showing 31 changed files with 207 additions and 149 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -38,9 +38,9 @@ public record OrderItemResponse(String name, int quantity, int price) {

public static OrderItemResponse from(final OrderItem orderItem) {
return new OrderItemResponse(
orderItem.getItem().getName(),
orderItem.getItemName(),
orderItem.getQuantity(),
orderItem.getItem().getPrice());
orderItem.getItemPrice());
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,6 @@ Page<Delivery> findRiderDeliveries(
@Query("select d from Delivery d"
+ " join fetch d.order o"
+ " join fetch o.orderItems oi"
+ " join fetch oi.item i"
+ " where d.deliveryId = :deliveryId")
Optional<Delivery> findByIdWithOrderAndItems(@Param("deliveryId") Long deliveryId);
}
Original file line number Diff line number Diff line change
Expand Up @@ -54,8 +54,8 @@ public FindEventDetailResponse findEventDetail(FindEventDetailCommand findEventD
eventItem.getItem().getName(),
eventItem.getItem().getPrice(),
eventItem.getItem().getDiscount(),
eventItem.getItem().getReviews().size(),
eventItem.getItem().getLikeItems().size(),
eventItem.getItem().getStatistics().getReviews(),
eventItem.getItem().getStatistics().getLikes(),
eventItem.getItem().getRate()
)
).collect(Collectors.toList());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ public record EventDetailResponse(Long eventId, String eventTitle, String eventD
}

public record EventItemResponse(Long itemId, String name, int price, int discount,
int reviewCount, int like, double rate) {
long reviewCount, long like, double rate) {

}
}
Expand Down
18 changes: 6 additions & 12 deletions src/main/java/com/prgrms/nabmart/domain/item/Item.java
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,9 @@
import com.prgrms.nabmart.domain.item.exception.InvalidItemException;
import com.prgrms.nabmart.domain.order.OrderItem;
import com.prgrms.nabmart.domain.review.Review;
import com.prgrms.nabmart.domain.statistics.Statistics;
import com.prgrms.nabmart.global.BaseTimeEntity;
import jakarta.persistence.CascadeType;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.FetchType;
Expand All @@ -15,6 +17,7 @@
import jakarta.persistence.JoinColumn;
import jakarta.persistence.ManyToOne;
import jakarta.persistence.OneToMany;
import jakarta.persistence.OneToOne;
import java.util.ArrayList;
import java.util.List;
import lombok.AccessLevel;
Expand Down Expand Up @@ -70,14 +73,8 @@ public class Item extends BaseTimeEntity {
@Column(nullable = false)
private boolean isDeleted = Boolean.FALSE;

@OneToMany(mappedBy = "item")
private List<Review> reviews = new ArrayList<>();

@OneToMany(mappedBy = "item")
private List<LikeItem> likeItems = new ArrayList<>();

@OneToMany(mappedBy = "item")
private List<OrderItem> orderItems = new ArrayList<>();
@OneToOne(mappedBy = "item", cascade = CascadeType.ALL)
private Statistics statistics;

@Builder
public Item(String name, int price, String description, int quantity, int discount,
Expand All @@ -95,16 +92,13 @@ public Item(String name, int price, String description, int quantity, int discou
this.maxBuyQuantity = maxBuyQuantity;
this.mainCategory = mainCategory;
this.subCategory = subCategory;
this.statistics = new Statistics(this);
}

public void decreaseQuantity(final int quantity) {
this.quantity -= quantity;
}

public void increaseQuantity(final int quantity) {
this.quantity += quantity;
}

public void updateItem(
final String name,
final int price,
Expand Down
Original file line number Diff line number Diff line change
@@ -1,9 +1,8 @@
package com.prgrms.nabmart.domain.item.repository;

import static com.prgrms.nabmart.domain.item.QItem.item;
import static com.prgrms.nabmart.domain.item.QLikeItem.likeItem;
import static com.prgrms.nabmart.domain.order.QOrderItem.orderItem;
import static com.prgrms.nabmart.domain.review.QReview.review;
import static com.prgrms.nabmart.domain.statistics.QStatistics.statistics;

import com.prgrms.nabmart.domain.category.MainCategory;
import com.prgrms.nabmart.domain.category.SubCategory;
Expand Down Expand Up @@ -40,13 +39,11 @@ public List<Item> findNewItemsOrderBy(Long lastIdx, Long lastItemId, ItemSortTyp

return queryFactory
.selectFrom(item)
.leftJoin(item.reviews, review)
.leftJoin(item.likeItems, likeItem)
.leftJoin(item.orderItems, orderItem)
.join(item.statistics, statistics)
.where(predicate)
.groupBy(item)
.having(
getHavingCondition(lastIdx, lastItemId, sortType)
getCondition(lastIdx, lastItemId, sortType)
)
.orderBy(orderSpecifier, item.itemId.asc())
.offset(pageable.getOffset())
Expand All @@ -61,18 +58,16 @@ public List<Item> findHotItemsOrderBy(Long lastIdx, Long lastItemId, ItemSortTyp
Predicate predicate = item.rate.gt(HOT_PRODUCT_REFERENCE_RATE);
Predicate orderCondition = JPAExpressions.select(orderItem.quantity.sum().coalesce(0))
.from(orderItem)
.where(orderItem.item.eq(item))
.where(orderItem.itemId.eq(item.itemId))
.gt(HOT_PRODUCT_REFERENCE_ORDERS);

return queryFactory
.selectFrom(item)
.leftJoin(item.reviews, review)
.leftJoin(item.likeItems, likeItem)
.leftJoin(item.orderItems, orderItem)
.where(predicate)
.join(item.statistics, statistics)
.where(predicate, getCondition(lastIdx, lastItemId, sortType))
.groupBy(item)
.having(
getHavingCondition(lastIdx, lastItemId, sortType),
getCondition(lastIdx, lastItemId, sortType),
orderCondition
)
.orderBy(orderSpecifier, item.itemId.asc())
Expand All @@ -88,9 +83,8 @@ public List<Item> findByMainCategoryOrderBy(MainCategory mainCategory, Long last
Predicate mainCategoryCondition = item.mainCategory.eq(mainCategory);
OrderSpecifier orderSpecifier = createOrderSpecifier(sortType);

return buildDataSetJPAQuery(sortType)
return queryFactory.selectFrom(item)
.where(mainCategoryCondition, getCondition(lastIdx, lastItemId, sortType))
.groupBy(item.itemId)
.orderBy(orderSpecifier, item.itemId.desc())
.limit(pageable.getPageSize())
.fetch();
Expand All @@ -104,41 +98,14 @@ public List<Item> findBySubCategoryOrderBy(MainCategory mainCategory, SubCategor
Predicate subCategoryCondition = item.subCategory.eq(subCategory);
OrderSpecifier orderSpecifier = createOrderSpecifier(sortType);

return buildDataSetJPAQuery(sortType)
return queryFactory.selectFrom(item)
.where(mainCategoryCondition, subCategoryCondition,
getCondition(lastIdx, lastItemId, sortType))
.groupBy(item.itemId)
.orderBy(orderSpecifier, item.itemId.desc())
.limit(pageable.getPageSize())
.fetch();
}

private JPAQuery<Item> buildDataSetJPAQuery(ItemSortType sortType) {
JPAQuery<Item> itemJPAQuery = queryFactory.selectFrom(item);
if (sortType.isPopular()) {
return itemJPAQuery
.leftJoin(item.orderItems, orderItem);
}
return itemJPAQuery;
}


private Predicate getHavingCondition(Long lastIdx, Long lastItemId, ItemSortType sortType) {
return switch (sortType) {
case NEW -> item.itemId.lt(lastIdx);
case HIGHEST_AMOUNT -> item.price.lt(lastIdx)
.or(item.price.eq(lastIdx.intValue()).and(item.itemId.gt(lastItemId)));
case LOWEST_AMOUNT -> item.price.gt(lastIdx)
.or(item.price.eq(lastIdx.intValue()).and(item.itemId.gt(lastItemId)));
case DISCOUNT -> item.discount.lt(lastIdx)
.or(item.discount.eq(lastIdx.intValue()).and(item.itemId.gt(lastItemId)));
default -> JPAExpressions.select(orderItem.quantity.longValue().sum().coalesce(0L))
.from(orderItem)
.where(orderItem.item.eq(item))
.lt(lastIdx);
};
}

private Predicate getCondition(Long lastIdx, Long lastItemId, ItemSortType sortType) {
return switch (sortType) {
case NEW -> item.itemId.lt(lastIdx);
Expand All @@ -148,10 +115,7 @@ private Predicate getCondition(Long lastIdx, Long lastItemId, ItemSortType sortT
.or(item.price.eq(lastIdx.intValue()).and(item.itemId.lt(lastItemId)));
case DISCOUNT -> item.discount.lt(lastIdx)
.or(item.discount.eq(lastIdx.intValue()).and(item.itemId.lt(lastItemId)));
default -> JPAExpressions.select(orderItem.quantity.longValue().sum().coalesce(0L))
.from(orderItem)
.where(orderItem.item.eq(item))
.lt(lastIdx);
default -> item.statistics.orders.lt(lastIdx);
};
}

Expand All @@ -162,7 +126,7 @@ private OrderSpecifier createOrderSpecifier(ItemSortType sortType) {
case HIGHEST_AMOUNT -> new OrderSpecifier<>(Order.DESC, item.price);
case LOWEST_AMOUNT -> new OrderSpecifier<>(Order.ASC, item.price);
case DISCOUNT -> new OrderSpecifier<>(Order.DESC, item.discount);
default -> new OrderSpecifier<>(Order.DESC, item.orderItems.any().quantity.sum());
default -> new OrderSpecifier<>(Order.DESC, item.statistics.orders);
};
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -93,9 +93,9 @@ public FindItemDetailResponse findItemDetail(FindItemDetailCommand findItemDetai
item.getDescription(),
item.getQuantity(),
item.getRate(),
item.getReviews().size(),
item.getStatistics().getReviews(),
item.getDiscount(),
item.getLikeItems().size(),
item.getStatistics().getLikes(),
item.getMaxBuyQuantity()
);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
import com.prgrms.nabmart.domain.item.service.request.FindLikeItemsCommand;
import com.prgrms.nabmart.domain.item.service.request.RegisterLikeItemCommand;
import com.prgrms.nabmart.domain.item.service.response.FindLikeItemsResponse;
import com.prgrms.nabmart.domain.statistics.StatisticsRepository;
import com.prgrms.nabmart.domain.user.User;
import com.prgrms.nabmart.domain.user.exception.NotFoundUserException;
import com.prgrms.nabmart.domain.user.repository.UserRepository;
Expand All @@ -27,6 +28,7 @@ public class LikeItemService {
private final UserRepository userRepository;
private final ItemRepository itemRepository;
private final LikeItemRepository likeItemRepository;
private final StatisticsRepository statisticsRepository;

@Transactional
public Long registerLikeItem(RegisterLikeItemCommand registerLikeItemCommand) {
Expand All @@ -35,6 +37,7 @@ public Long registerLikeItem(RegisterLikeItemCommand registerLikeItemCommand) {
checkDuplicateLikedItem(user, item);
LikeItem likeItem = new LikeItem(user, item);
likeItemRepository.save(likeItem);
statisticsRepository.increaseLikes(item.getItemId());
return likeItem.getLikeItemId();
}

Expand All @@ -45,6 +48,7 @@ public void deleteLikeItem(DeleteLikeItemCommand deleteLikeItemCommand) {
throw new UnauthorizedLikeItemException("권한이 없습니다.");
}
likeItemRepository.delete(likeItem);
statisticsRepository.decreaseLikes(likeItem.getItem().getItemId());
}

private void checkDuplicateLikedItem(final User user, final Item item) {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
package com.prgrms.nabmart.domain.item.service.response;

public record FindItemDetailResponse(Long itemId, String name, int price, String description,
int quantity, double rate, int reviewCount, int discount,
int like, int maxBuyQuantity) {
int quantity, double rate, long reviewCount, int discount,
long like, int maxBuyQuantity) {

public static FindItemDetailResponse of(final Long itemId, final String name, final int price,
final String description,
final int quantity,
final double rate, final int reviewCount, final int discount, final int like,
final double rate, final long reviewCount, final int discount, final long like,
final int maxBuyQuantity) {
return new FindItemDetailResponse(itemId, name, price, description, quantity, rate,
reviewCount, discount, like, maxBuyQuantity);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,12 +14,12 @@ public static FindItemsResponse from(final List<Item> items) {
}

public record FindItemResponse(Long itemId, String name, int price, int discount,
int reviewCount, int like, double rate) {
long reviewCount, long like, double rate) {

public static FindItemResponse from(final Item item) {
return new FindItemResponse(
item.getItemId(), item.getName(), item.getPrice(), item.getDiscount(),
item.getReviews().size(), item.getLikeItems().size(), item.getRate()
item.getStatistics().getReviews(), item.getStatistics().getLikes(), item.getRate()
);
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,8 +25,8 @@ public record FindLikeItemResponse(
String name,
int price,
int discount,
int reviewCount,
int like,
Long reviewCount,
Long like,
double rate) {

public static FindLikeItemResponse from(final LikeItem likeItem) {
Expand All @@ -37,8 +37,8 @@ public static FindLikeItemResponse from(final LikeItem likeItem) {
item.getName(),
item.getPrice(),
item.getDiscount(),
item.getReviews().size(),
item.getLikeItems().size(),
item.getStatistics().getReviews(),
item.getStatistics().getLikes(),
item.getRate());
}
}
Expand Down
4 changes: 2 additions & 2 deletions src/main/java/com/prgrms/nabmart/domain/order/Order.java
Original file line number Diff line number Diff line change
Expand Up @@ -89,8 +89,8 @@ public void updateOrderStatus(OrderStatus orderStatus) {

private void createOrderName(final List<OrderItem> orderItems) {
this.name = (orderItems.size() == 1) ?
orderItems.get(0).getItem().getName() :
orderItems.get(0).getItem().getName() + "외 " + (orderItems.size() - 1) + "개";
orderItems.get(0).getItemName() :
orderItems.get(0).getItemName() + "외 " + (orderItems.size() - 1) + "개";
}

private void setOrderItems(final List<OrderItem> orderItems) {
Expand Down
17 changes: 12 additions & 5 deletions src/main/java/com/prgrms/nabmart/domain/order/OrderItem.java
Original file line number Diff line number Diff line change
Expand Up @@ -32,17 +32,24 @@ public class OrderItem extends BaseTimeEntity {
@JoinColumn(name = "order_id")
private Order order;

@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "item_id")
private Item item;
@Column(nullable = false)
private Long itemId;

@Column(nullable = false)
private String itemName;

@Column(nullable = false)
private int itemPrice;

public OrderItem(Item item, int quantity) {
this.item = item;
this.itemId = item.getItemId();
this.itemPrice = item.getPrice();
this.itemName = item.getName();
this.quantity = quantity;
}

public int calculateSubtotal() {
return item.getPrice() * quantity;
return itemPrice * quantity;
}

public void setOrder(Order order) {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,18 +1,8 @@
package com.prgrms.nabmart.domain.order.repository;

import com.prgrms.nabmart.domain.item.Item;
import com.prgrms.nabmart.domain.order.OrderItem;
import java.util.Optional;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;

public interface OrderItemRepository extends JpaRepository<OrderItem, Long> {

Optional<OrderItem> findByItem(Item item);

@Query("SELECT SUM(oi.quantity) "
+ "FROM OrderItem oi "
+ "WHERE oi.item.id = :itemId")
Long countByOrderItemId(@Param("itemId") Long itemId);
}
Loading

0 comments on commit 23652e4

Please sign in to comment.