[01.20] 내일배움캠프[Spring] TIL-57
1. Spring Project
검색기능과 페이징 기능의 콜라보
- 유저의 리스트, 판매상품리스트, 판매자의 리스트 등 페이징 처리가 들어간 곳에 검색기능을 넣어보았다.
Containing의 발견
- 보통 판매상품이름 : 맥북프로 -> 검색어 : 프로 이런식으로 검색할 때 쿼리
select * from product p where p.productName = Like %keyword%
- 이런식의 쿼리가 나가게 되는데, 쿼리를 만들어주는 JPA에도 이런 쿼리를 만들어주는 과정이 있었다.
Page<Product> findByProductNameContaining(String keyword, Pageable pageable);
- 이런식으로 어떠한 것을 keyword로 찾을 것 인지 작성하여 간단하게 구현했다.
문제점
Product
를 상품이름이 아닌, 판매자의 이름으로 조회할 경우
-> 현재 Product
엔티티에는 sellerId
의 필드는 존재하지만 userName
필드는 없다. 근데 우리는 필요로 한다.
방법1
@Entitiy
public class Product{
@ManyToOne
@JoinColume(name="")
private User user;
}
- 이렇게 진행하면
Product.getUser()....
해서 해당 Product
객체에 연관 된 User
의 정보를 사용할 수 있다.
방법2(이걸 사용, 현재 프로젝트는 Id참조 형태로 구성..)
@Query("select new com.sparta.morningworkout.dto.search.ProductResponseSearchByNameDto(p.productName,p.price,u.username,p.category)" +
" from users u LEFT join Product p on u.id = p.userId where u.role= 'SELLER' AND u.username like %:sellerName%")
Page<ProductResponseSearchByNameDto> findAllBySellerName(String sellerName, Pageable pageable);
@Query("select new com.sparta.morningworkout.dto.product.ProductResponseDto(p.productName,p.price,p.category) from Product p where p.userId=:sellerId AND p.productName like %:keyword%")
Page<ProductResponseDto> findAllBySellerIdByProductName(String keyword, long sellerId, Pageable pageable);
- JPQL은 기존에 알았던 SQL과 살짝 형식이 달라서 조금 고생했다..
- 하지만 Join쿼리를 직접 사용함으로써, 불필요한 연관관계를 끊을 수 있었다.