Skip to content

Commit

Permalink
refactor: fetch join으로 n+1 제거
Browse files Browse the repository at this point in the history
  • Loading branch information
xxeol2 committed Sep 20, 2023
1 parent 4c747af commit e9bbeee
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import com.festago.stage.domain.Stage;
import java.util.List;
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;
Expand All @@ -15,4 +16,12 @@ public interface StageRepository extends JpaRepository<Stage, Long> {
WHERE s.festival.id = :festivalId
""")
List<Stage> findAllDetailByFestivalId(@Param("festivalId") Long festivalId);

@Query("""
SELECT s FROM Stage s
LEFT JOIN s.festival f
LEFT JOIN f.school sc
WHERE s.id = :id
""")
Optional<Stage> findByIdWithFetch(@Param("id") Long id);
}
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,6 @@ public TicketService(TicketRepository ticketRepository, StageRepository stageRep
public TicketCreateResponse create(TicketCreateRequest request) {
Stage stage = findStageById(request.stageId());
TicketType ticketType = request.ticketType();
// TODO: n+1
School school = stage.getFestival().getSchool();

Ticket ticket = ticketRepository.findByTicketTypeAndStage(ticketType, stage)
Expand All @@ -45,7 +44,7 @@ public TicketCreateResponse create(TicketCreateRequest request) {
}

private Stage findStageById(Long stageId) {
return stageRepository.findById(stageId)
return stageRepository.findByIdWithFetch(stageId)
.orElseThrow(() -> new NotFoundException(ErrorCode.STAGE_NOT_FOUND));
}

Expand Down

0 comments on commit e9bbeee

Please sign in to comment.