오늘의 학습 키워드
이벤트-상품 중간 테이블
QueryDSL 삭제 쿼리
QueryDSL 3개 테이블 조인
@Getter
@Entity
@NoArgsConstructor
@AllArgsConstructor
public class EventProduct {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "event_id")
private Event event;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "product_id")
private Product product;
public EventProduct(Event event, Product product) {
this.event = event;
this.product = product;
}
}
@Getter
public class EventProductRequest {
private Long productId;
}
@Getter
public class EventRequest {
@NotNull(message = "이벤트를 등록하시려면 제목을 입력하세요.")
private String title;
@NotNull(message = "이벤트를 등록하시려면 내용을 입력하세요.")
private String content;
private Long limitNum;
@NotNull(message = "이벤트를 등록하시려면 오픈일자를 입력하세요.")
@DateTimeFormat(pattern = "yyyy-MM-dd")
private LocalDate openAt;
private List<EventProductRequest> eventProducts;
}
@Transactional
public Long createEvent(EventRequest eventRequest, User user) {
Event event = new Event(eventRequest, user);
Event savedEvent = eventRepository.save(event);
eventRequest.getEventProducts().stream()
.map(EventProductRequest::getProductId)
.map(productId -> productRepository.findById(productId)
.orElseThrow(() -> new IllegalArgumentException("존재하지 않는 상품입니다.")))
.map(product -> new EventProduct(savedEvent, product))
.forEach(eventProductRepository::save);
return savedEvent.getId();
}
@Transactional
public void deleteEventProduct(Long eventProductId, User user) {
EventProduct eventProduct = eventProductRepository.findById(eventProductId)
.orElseThrow(() -> new IllegalArgumentException("해당 이벤트 상품은 존재하지 않습니다."));
eventProductRepository.delete(eventProduct);
}
@Transactional
public void deleteEvent(Long eventId, User user) {
Event event = findEvent(eventId);
if (!event.getUser().getId().equals(user.getId())) {
throw new InvalidAdminEventException(INVALID_ADMIN_EVENT);
}
eventQuery.deleteEventProduct(eventId);
eventRepository.delete(event);
}
public void deleteEventProduct(Long eventId) {
long count = jpaQueryFactory.delete(QEventProduct.eventProduct)
.where(QEventProduct.eventProduct.event.id.eq(eventId))
.execute();
}