[인프런 워밍업 클럽 0기] BE 4일차 과제

[인프런 워밍업 클럽 0기] BE 4일차 과제

우리는 GET API와 POST API를 만드는 방법을 배웠습니다. 👍 추가적인 API 들을 만들어 보며 API 개발에 익숙해져 봅시다!

  • Request

public class FruitRequest {

    private String name;
    private LocalDate warehousingDate;
    private long price;

    public String getName() {
        return name;
    }

    public LocalDate getWarehousingDate() {
        return warehousingDate;
    }

    public long getPrice() {
        return price;
    }
}

 

  • Controller

@RequestMapping("/api/v1")
@RestController
public class FruitController {

    JdbcTemplate jdbcTemplate;

    public FruitController(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }

    @PostMapping("/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());
    }
}

  • postman

image

  • DB

image


  • Controller

@PutMapping("/fruit")
public void putFruit(@RequestBody FruitSellRequest request) {
    String readSql = "SELECT * FROM fruit WHERE id = ?";
    boolean isFruitNotExist = jdbcTemplate.query(readSql, (rs, rowNum) -> 0, request.getId()).isEmpty();

    if (isFruitNotExist) {
        throw new IllegalArgumentException();
    }

    String sql = "UPDATE fruit SET is_sold = 1 WHERE id = ?";
    jdbcTemplate.update(sql, request.getId());
}

 

  • request

public class FruitSellRequest {
    private long id;

    public long getId() {
        return id;
    }
}

  • postman

image

  • DB

image


  • Controller

@GetMapping("/fruit/stat")
public FruitStatResponse getStat(@RequestParam String name) {
    String salesSql = "select sum(price) from fruit where is_sold = 1 group by name having name = ?";
    String notSalesSql = "select sum(price) from fruit where is_sold = 0 group by name having name = ?";

    long salesAmount = jdbcTemplate.queryForObject(salesSql, Long.class, name);
    long notSalesAmount = jdbcTemplate.queryForObject(notSalesSql, Long.class, name);

    return new FruitStatResponse(salesAmount, notSalesAmount);
}

 

  • response

public class FruitStatResponse {

    private long salesAmount;
    private long notSalesAmount;

    public FruitStatResponse(long salesAmount, long notSalesAmount) {
        this.salesAmount = salesAmount;
        this.notSalesAmount = notSalesAmount;
    }

    public long getSalesAmount() {
        return salesAmount;
    }

    public long getNotSalesAmount() {
        return notSalesAmount;
    }
}

 

  • postman

image

  • DB

image

댓글을 작성해보세요.

채널톡 아이콘