문제 1. 입고된 과일 정보 저장 API
DB
create table fruit (
id bigint auto_increment,
name varchar(25),
warehousingDate date,
price int,
sold ENUM('SOLD', 'NOT_SOLD') DEFAULT 'NOT_SOLD',
primary key (id)
);
sold ENUM('SOLD', 'NOT_SOLD') DEFAULT 'NOT_SOLD'
- ENUM 타입을 통해 판매 여부를
‘SOLD’
, ‘NOT_SOLD’
의 두 가지 상태로만 나타냄
- NOT_SOLD를 기본 값으로 설정
DTO
@Getter
public class FruitRequest {
private long id;
private String name;
private LocalDate warehousingDate;
private long price;
}
Controller
@RestController
public class FruitController {
private final JdbcTemplate jdbcTemplate;
public FruitController(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
@PostMapping("/api/v1/fruit")
public void saveFruit(@RequestBody FruitRequest request) {
String sql = "insert into fruit (name, warehousingDate, price) values (?, ?, ?)";
jdbcTemplate.update(sql,
request.getName(), request.getWarehousingDate(), request.getPrice()
);
}
}
Result


문제 2. 판매된 과일 정보 기록 API
Controller
@PutMapping("/api/v1/fruit")
public void updateFruit(@RequestBody FruitRequest request) {
// 과일이 존재하는지 확인
String readSql = "SELECT * FROM fruit WHERE id = ?";
boolean isFruitNotExit
= jdbcTemplate.query(readSql, (rs, rowNum) -> 0, request.getId()).isEmpty();
if (isFruitNotExit) {
throw new IllegalStateException();
}
String sql = "UPDATE fruit SET sold = 'SOLD' WHERE id = ?";
jdbcTemplate.update(sql, request.getId());
}
Result
