Spring/JSCODE - Spring

4회차 - 연습문제 (3)

YooKyungHun 2023. 3. 19. 22:05

문제

상품 조회 api 역할 구분하기

 

controller, service, repository 구분하기

학습목표 - controller, service, repository가 각각 어떤 역할을 하는지 이해한다. - 하나의 api를 구현할 때 controller, service, repository로 계층을 나눠서 구현할 수 있다.

jscode.notion.site

 

풀이

@RestController
@RequestMapping("api/products")
public class ProductController3 {
private final ProductService3 productService;
public ProductController3(ProductService3 productService) {
this.productService = productService;
}
// 상품 조회
@GetMapping("/id/{id}")
public Product3 getProductInfo(@PathVariable("id") String id) {
return productService.getProductInfo(Integer.valueOf(id));
}
}
@Service
public class ProductService3 {
private final ProductRepository3 productRepository;
public ProductService3(ProductRepository3 productRepository) {
this.productRepository = productRepository;
}
public Product3 getProductInfo(Integer id) {
Product3 product = productRepository.getProductInfo(id);
product.setPrice(product.getPrice()/1300);
return product;
}
}
@Repository
public class ProductRepository3 {
private final List<Product3> products = List.of(
new Product3(1000, "키보드", 10000L),
new Product3(1001, "마우스", 20000L),
new Product3(1002, "모니터", 30000L)
);
public Product3 getProductInfo(Integer id) {
for (Product3 product: products) {
if (product.getId().equals(id)) {
return product;
}
}
return null;
}
}
package com.jscode.spring.day04.Example3;
import lombok.Getter;
import lombok.Setter;
@Getter
@Setter
public class Product3 {
private Integer id;
private final String name;
private Long price;
public Product3(Integer id, String name, Long price) {
this.id = id;
this.name = name;
this.price = price;
}
}

 

'Spring > JSCODE - Spring' 카테고리의 다른 글

4회차 - 미션 (2)  (0) 2023.03.19
4회차 - 미션 (1)  (0) 2023.03.19
4회차 - 연습문제 (2)  (0) 2023.03.19
4회차 - 연습문제 (1)  (0) 2023.03.19
3회차 - 연습문제  (0) 2023.03.13