인프런 워밍업 스터디 BE 4일

문제 1

@PostMapping("/api/v1/fruit")
public void saveFruit(@RequestBody FruitCreateRequest fruitCreateRequest) {
    String sql = "INSERT INTO fruit (name, price, stocked_date, sold) values (?, ?, ?, ?)";
    jdbcTemplate.update(sql, fruitCreateRequest.getName(),
            fruitCreateRequest.getPrice(),
            fruitCreateRequest.getWarehousingDate(),
            false);
}

 

문제2

@PutMapping("/api/v1/fruit")
public void updateFruit(@RequestBody FruitUpdateRequest fruitUpdateRequest){
    String readSql = "SELECT * FROM fruit WHERE id = ?";
    boolean isUserNotExist = jdbcTemplate.query(readSql, (rs, rowNum) -> 0, fruitUpdateRequest.getId()).isEmpty();
    if (isUserNotExist) {
        throw new IllegalArgumentException();
    }

    String sql = "UPDATE fruit SET sold = ? WHERE id = ?";
    jdbcTemplate.update(sql, true, fruitUpdateRequest.getId());
}

 

문제3

@GetMapping("/api/v1/fruit/stat")
public FruitSaleResponse howManySale(@RequestParam String name) {
    String readSql = "SELECT * FROM fruit WHERE name = ?";
    boolean isUserNotExist = jdbcTemplate.query(readSql, (rs, rowNum) -> 0, name).isEmpty();
    if (isUserNotExist) {
        throw new IllegalArgumentException();
    }

    String sqlSold = "SELECT * FROM fruit WHERE name = ? AND sold = 1";
    String sqlNotSold = "SELECT * FROM fruit WHERE name = ? AND sold = 0";

    List<Integer> sqlSoldList = jdbcTemplate.query(sqlSold, new RowMapper<Integer>() {
        @Override
        public Integer mapRow(ResultSet rs, int rowNum) throws SQLException {
            return rs.getInt("price");
        }
    }, name);

    List<Integer> sqlNotSoldList = jdbcTemplate.query(sqlNotSold, new RowMapper<Integer>() {
        @Override
        public Integer mapRow(ResultSet rs, int rowNum) throws SQLException {
            return rs.getInt("price");
        }
    }, name);

    Integer salePrice = 0;
    for (int i = 0; i < sqlSoldList.size(); i++) {
        salePrice += sqlSoldList.get(i);
    }

    Integer notSalePrice = 0;
    for (int i = 0; i < sqlNotSoldList.size(); i++) {
        notSalePrice += sqlNotSoldList.get(i);
    }

    return new FruitSaleResponse(salePrice, notSalePrice);
}

댓글을 작성해보세요.

채널톡 아이콘