[인프런 워밍업 클럽] 6일차
9개월 전
진도표 6일차와 연결됩니다
우리는 스프링 컨테이너의 개념을 배우고, 기존에 작성했던 Controller 코드를 3단 분리해보았습니다. 앞으로 API를 개발할 때는 이 계층에 맞게 각 코드가 작성되어야 합니다! 🙂
과제 #4 에서 만들었던 API를 분리해보며, Controller - Service - Repository 계층에 익숙해져 봅시다! 👍
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.sql.Date;
import java.util.Map;
@RestController
public class FruitController {
private final FruitService fruitService;
public FruitController(FruitService fruitService) {
this.fruitService = fruitService;
}
@PostMapping("/api/v1/fruit")
public void saveFruit(@RequestBody FruitCreateRequest request) {
fruitService.saveFruit(request.getName(), Date.valueOf(request.getWarehousingDate()), request.getPrice());
}
@PutMapping("/api/v1/fruit")
public ResponseEntity<String> markAsSoldOut(@RequestBody Map<String, Long> body) {
Long id = body.get("id");
if (id == null) {
return ResponseEntity.badRequest().body("id 누락");
}
fruitService.markAsSoldOut(id);
return ResponseEntity.ok("'soldout'");
}
@GetMapping("/api/v1/fruit/stat")
public Map<String, Long> getSalesStat() {
return fruitService.getSalesStat();
}
}
import org.springframework.stereotype.Service;
import java.sql.Date;
import java.util.Map;
@Service
public class FruitService {
private final FruitRepository fruitRepository;
public FruitService(FruitRepository fruitRepository) {
this.fruitRepository = fruitRepository;
}
public void saveFruit(String name, Date warehousingDate, Long price) {
fruitRepository.saveFruit(name, warehousingDate, price);
}
public void markAsSoldOut(Long id) {
fruitRepository.markAsSoldOut(id);
}
public Map<String, Long> getSalesStat() {
return fruitRepository.getSalesStat();
}
}
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
import java.sql.Date;
import java.util.HashMap;
import java.util.Map;
@Repository
public class FruitRepository {
private final JdbcTemplate jdbcTemplate;
public FruitRepository(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
public void saveFruit(String name, Date warehousingDate, Long price) {
String sql = "INSERT INTO fruits(name, warehousingDate, price) VALUES(?, ?, ?)";
jdbcTemplate.update(sql, name, warehousingDate, price);
}
public void markAsSoldOut(Long id) {
String sql = "UPDATE fruits SET status = 'soldout' WHERE id = ?";
jdbcTemplate.update(sql, id);
}
public Map<String, Long> getSalesStat() {
String salesAmountSql = "SELECT SUM(price) FROM fruits WHERE status = 'soldout'";
String naoSalesAmountSql = "SELECT SUM(price) FROM fruits WHERE status IS NULL OR status != 'soldout'";
Long salesAmount = jdbcTemplate.queryForObject(salesAmountSql, Long.class);
Long naoSalesAmount = jdbcTemplate.queryForObject(naoSalesAmountSql, Long.class);
Map<String, Long> result = new HashMap<>();
result.put("salesAmount", salesAmount != null ? salesAmount : 0);
result.put("naoSalesAmount", naoSalesAmount != null ? naoSalesAmount : 0);
return result;
}
}
댓글을 작성해보세요.