[인프런 워밍업 클럽 BE 0기] 4일차 과제
9개월 전
문제 1
먼저 데이터베이스 테이블을 생성한다.
create table fruit (
id bigint auto_increament,
name varchar(25),
warehousingDate date,
price long,
primary key (id)
)
컨트롤러 과일 저장 코드
@RestController
public class FruitController {
private JdbcTemplate jdbcTemplate;
public FruitController(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
// 문제 1
@PostMapping("/api/v1/fruit")
@ResponseStatus(HttpStatus.OK)
public void saveFruit(@RequestBody Fruit fruit) {
String sql = "insert into fruit (name, warehousingDate, price) values (?, ?, ?)";
jdbcTemplate.update(sql, fruit.getName(), fruit.getWareHousingDate(), fruit.getPrice());
}
}
과일 저장 DTO
public class Fruit {
private String name;
private LocalDate wareHousingDate;
private long price;
public Fruit(String name, LocalDate wareHousingDate, long price) {
this.name = name;
this.wareHousingDate = wareHousingDate;
this.price = price;
}
public String getName() {
return name;
}
public LocalDate getWareHousingDate() {
return wareHousingDate;
}
public long getPrice() {
return price;
}
}
문제 2
table에 is_sold 컬럼 추가
Fruit 클래스에 isSold 필드 추가
컨트롤러에 코드 추가
@PutMapping("/api/v1/fruit")
@ResponseStatus(HttpStatus.OK)
public void sellFruit(@RequestBody FruitSellRequest fruitSellRequest) {
String sql = "UPDATE fruit set is_sold = true where id = ?";
jdbcTemplate.update(sql, fruitSellRequest.getId());
}
과일 판매 DTO
public class FruitSellRequest {
private long id;
public FruitSellRequest(long id) {
this.id = id;
}
public long getId() {
return id;
}
}
문제 3
컨트롤러에 과일 통계 요청 처리 메서드 추가
@GetMapping("/api/v1/fruit/stat")
public Map<String, Long> fruitStat(@RequestParam String name) {
long soldAmount = calculateSoldAmount(name);
long unsoldAmount = calculateUnsoldAmount(name);
Map<String, Long> result = new HashMap<>();
result.put("soldAmount", soldAmount);
result.put("unsoldAmount", unsoldAmount);
return result;
}
public long calculateSoldAmount(String name) {
String sql = "select sum(price) from fruit where name = ? and is_sold = true";
return jdbcTemplate.queryForObject(sql, new Object[]{name}, Long.class);
}
public long calculateUnsoldAmount(String name) {
String sql = "select sum(price) from fruit where name = ? and is_sold = false";
return jdbcTemplate.queryForObject(sql, new Object[]{name}, Long.class);
}
댓글을 작성해보세요.