랄라
[TIL 10일차] 25.02.25 본문
프로젝트 마무리로 진행한 기능의 상세설명을 기록하기로 했다.
검색 필터링 기능 - Specification 사용
Specifications :: Spring Data JPA
Specifications :: Spring Data JPA
Example 4. Using a Specification to delete entries. Specification ageLessThan18 = (root, query, cb) -> cb.lessThan(root.get("age").as(Integer.class), 18) userRepository.delete(ageLessThan18); The Specification builds up a criteria where the age field (cast
docs.spring.io
Query DSL과 비교했을 때, Specification은 상대적으로 간편하고 명확한 구조를 가지고 있으며, 구현 중이던 API의 쿼리 로직이 복잡하지 않았기 때문에 더 효율적인 코드 작성을 위해 해당 기능을 선택했습니다.
사용방법(RestaurantService)
searchRestaurant 내부에 조건을 설정할 수 있도록 Specification객체 작성
Specification<Restaurant> spec = Specification.where(RestaurantSpecification.hasName(name))
.and(RestaurantSpecification.hasCategory(categoryId))
.and(RestaurantSpecification.haslegalCode(legalCode))
.and(RestaurantSpecification.isNotDeleted());
가게 검색 필터링 기능에 평균평점이 함께 조회되도록 구현 - JPQL 사용
@Query("SELECT AVG(rv.rating) AS avg_rating FROM Review rv JOIN Order o ON rv.order.id = o.id JOIN Menu m ON o.menu.id = m.id JOIN Restaurant rt ON m.restaurant.id = rt.id WHERE rt.id = :restaurantId")
public Double getRestaurantAverageRating(@Param("restaurantId") UUID restaurantId);
평균 평점값만 불러오도록 쿼리문을 작성하고, 기존에 작성된 가게 정보와 함께 출력하기위해
검색용 responseDto를 작성하여 평균평점 컬럼에 값을 추가하였습니다.
'내일배움캠프 > TIL' 카테고리의 다른 글
| [TIL 12일차] 25.02.27 (0) | 2025.02.27 |
|---|---|
| [TIL 11일차] 25.02.26 (0) | 2025.02.27 |
| [TIL 9일차] 25.02.21 (0) | 2025.02.21 |
| [TIL 8일차] 25.02.20 (0) | 2025.02.20 |
| [TIL 7일차] 25.02.18 (0) | 2025.02.18 |