Skip to content

Commit

Permalink
refactor: 쿼리 1번으로 조회할 수 있도록 튜닝, 가장 최근 즐겨찾기 사진을 가져오도록 수정
Browse files Browse the repository at this point in the history
  • Loading branch information
Dompoo committed Sep 4, 2024
1 parent 98b9127 commit bfa1af6
Show file tree
Hide file tree
Showing 3 changed files with 9 additions and 15 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -52,9 +52,9 @@ class MyPlantService(
now: LocalDate,
user: User,
): List<MyPlantResponse> {
val myPlants = findMyPlantsWithFavoriteImageByUser(user)
val myPlantsWithImageUrl: List<MyPlantWithImageUrl> = imageRepository.findMyPlantAndMostRecentFavoriteImageByUser(user)

return MyPlantResponse.fromMyPlantWithImageUrlList(myPlants, now)
return MyPlantResponse.fromMyPlantWithImageUrlList(myPlantsWithImageUrl, now)
}

@Transactional(readOnly = true)
Expand Down Expand Up @@ -165,12 +165,4 @@ class MyPlantService(

return HealthCheckResponse(myPlantMessageFactory.createHealthCheckMessage())
}

private fun findMyPlantsWithFavoriteImageByUser(user: User): List<MyPlantWithImageUrl> {
// user가 가지고 있는 MyPlant 리스트를 쿼리
val myPlants: List<MyPlant> = myPlantRepository.findAllByUser(user)

// MyPlant-imageUrl을 Location을 페치조인하여 쿼리
return imageRepository.findFavoriteImagesForMyPlants(myPlants)
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -18,17 +18,19 @@ interface ImageRepository : JpaRepository<Image, Long> {
FROM Image i
JOIN i.myPlant mp
JOIN FETCH mp.location l
WHERE mp IN :myPlants
WHERE mp.user = :user
AND i.favorite = true
AND i.id = (
SELECT MIN(i2.id)
AND i.updatedDate = (
SELECT MAX(i2.updatedDate)
FROM Image i2
WHERE i2.myPlant = mp
AND i2.favorite = true
)
""",
)
fun findFavoriteImagesForMyPlants(myPlants: List<MyPlant>): List<MyPlantWithImageUrl>
fun findMyPlantAndMostRecentFavoriteImageByUser(
@Param("user") user: User,
): List<MyPlantWithImageUrl>

@Modifying
@Query(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -139,7 +139,7 @@ class MyPlantServiceTest : DescribeSpec(
}
every { myPlantRepsitory.findAllByUser(any()) } returns
listOf(myPlant1, myPlant2, myPlant3)
every { imageRepository.findFavoriteImagesForMyPlants(any()) } returns
every { imageRepository.findMyPlantAndMostRecentFavoriteImageByUser(any()) } returns
listOf(
MyPlantWithImageUrl(myPlant1, "url1"),
MyPlantWithImageUrl(myPlant2, "url2"),
Expand Down

0 comments on commit bfa1af6

Please sign in to comment.