상품 : 회원 = N : 1
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "user_id", nullable = false)
private User user;
// 관심 상품 등록하기
@PostMapping("/products")
public ProductResponseDto createProduct(@RequestBody ProductRequestDto requestDto, @AuthenticationPrincipal UserDetailsImpl userDetails) {
// 응답 보내기
return productService.createProduct(requestDto, userDetails.getUser());
}
// 관심 상품 조회하기
@GetMapping("/products")
public List<ProductResponseDto> getProducts(@AuthenticationPrincipal UserDetailsImpl userDetails) {
// 응답 보내기
return productService.getProducts(userDetails.getUser());
}
public ProductResponseDto createProduct(ProductRequestDto requestDto, User user) {
Product product = productRepository.save(new Product(requestDto, user));
return new ProductResponseDto(product);
}
public List<ProductResponseDto> getProducts(User user) {
List<Product> productList = productRepository.findALlByUser(user);
List<ProductResponseDto> responseDtoList = new ArrayList<>();
for (Product product : productList) {
responseDtoList.add(new ProductResponseDto(product));
}
return responseDtoList;
}
public interface ProductRepository extends JpaRepository<Product, Long> {
List<Product> findALlByUser(User user);
}
Admin 계정 모든 상품 조회 기능 추가
// 관리자 조회
@GetMapping("/admin/products")
public List<ProductResponseDto> getAllProducts() {
return productService.getAllProducts();
}
public List<ProductResponseDto> getAllProducts() {
List<Product> productList = productRepository.findAll();
List<ProductResponseDto> responseDtoList = new ArrayList<>();
for (Product product : productList) {
responseDtoList.add(new ProductResponseDto(product));
}
return responseDtoList;
}