[인프런 워밍업 클럽] 4차 과제

문제풀기 전에 간단하게 테이블을 생성하였음

create table fruit
(
    id              bigint auto_increment primary key,
    name            varchar(20),
    warehousingDate date,
    price           long,
    is_sold boolean default 0,
);

생성자를 만들어 주었음 (dto)

 

<1번 문제>

과일정보를 저장하는 API를 만들어 보기

 @PostMapping("/api/v1/fruit")
    public void saveFruit(@RequestBody FruitInfoRequest request) {
        String sql = "insert into fruit (name, warehousingDate, price) values (?, ?, ?)";    // 쿼리 작성
        jdbcTemplate.update(sql, request.name(), request.warehousingDate(), request.price());
    }

 

<2번 문제>

과일이 팔리게 되면, 우리 시스템에 팔린 과일 정보를 기록

@PutMapping("/api/v1/fruit")
    public void updateFruit(@RequestBody FruitIdRequest request) {
        String readSql = "select * from fruit where id = ?";
        boolean isFruitNotExist = jdbcTemplate.query(readSql, (rs, rowNum) -> 0, request.id()).isEmpty();
        if (isFruitNotExist) {
            throw new IllegalArgumentException("해당하는 과일이 존재하지 않습니다.");
        }  //예외처리 작성

        String sql = "update fruit set is_sold = 1 where id = ?";  // 쿼리 작성
        jdbcTemplate.update(sql, request.id());
    }
}

 

<3번 문제>

특정 과일을 기준으로 팔린 금액, 팔리지 않은 금액 조회

@GetMapping("/api/v1/fruit/stat")
    public FruitAmountResponse getAmount(@RequestParam String name) {
        String readSql = "select * from fruit where name = ?";
        boolean isFruitNotExist = jdbcTemplate.query(readSql, (rs, rowNum) -> 0, name).isEmpty();
        if (isFruitNotExist) {
            throw new IllegalArgumentException("해당하는 과일이 존재하지 않습니다.");
        } //예외처리 작성

        String sql1 = "select sum(price) as salesAmount from fruit where is_sold = 1";
        String sql2 = "select sum(price) as notSalesAmount from fruit where is_sold = 0";

        Long salesAmount = jdbcTemplate.queryForObject(sql1, (rs, rowNum) -> rs.getLong("salesAmount"));
        Long notSalesAmount = jdbcTemplate.queryForObject(sql2, (rs, rowNum) -> rs.getLong("notSalesAmount"));

        return new FruitAmountResponse(salesAmount, notSalesAmount);
    }
}

 

 

댓글을 작성해보세요.

채널톡 아이콘