[인프런워밍업스터디_BE_0기] 네 번째 과제!

평소에도 부족하지만 오늘은 정말 시간이 부족했다..ㅠ 우선 코드를 올리고 주말을 활용해서 글을 다듬어야할 것 같다..

 

컨트롤러 클래스

@RestController
public class FruitController {

    private final JdbcTemplate jdbcTemplate;

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

    @PostMapping("/api/v1/fruit")
    public void storeFruit(@RequestBody FruitStoreRequest request) {
        String sql = "insert into fruit (name, warehousing_date, price) values (?, ?, ?)";
        jdbcTemplate.update(sql, request.getName(), request.getWarehousingDate(), request.getPrice());
    }

    @PutMapping("/api/v1/fruit")
    public void sellFruit(@RequestBody FruitSellReqeust reqeust) {
        String sql = "update fruit set sold_yn = 'Y' where id = ?";
        jdbcTemplate.update(sql, reqeust.getId());
    }

    @GetMapping("/api/v1/fruit/stat")
    public FruitStatResponse getStat(@RequestParam String name) {
        String sql = "select sold_yn, sum(price) as amount from fruit where name = ? group by sold_yn";
        List<FruitStat> stats = jdbcTemplate.query(sql,
                new Object[]{name},
                (rs, rowNum) -> new FruitStat(rs.getString("sold_yn"), rs.getLong("amount")));

        FruitStatResponse response = new FruitStatResponse();
        stats.forEach(response::setStat);
        return response;
    }
}

 

모델

public class FruitStat {
    private String soldYn;
    private long amount;

    public FruitStat(String soldYn, long amount) {
        this.soldYn = soldYn;
        this.amount = amount;
    }

    public String getSoldYn() {
        return soldYn;
    }

    public long getAmount() {
        return amount;
    }
}

 

요청 클래스

public class FruitSellReqeust {
    private long id;

    public long getId() {
        return id;
    }
}

public class FruitStoreRequest {
    private String name;
    private LocalDate warehousingDate;
    private long price;

    public String getName() {
        return name;
    }

    public LocalDate getWarehousingDate() {
        return warehousingDate;
    }

    public long getPrice() {
        return price;
    }
}

 

응답 클래스

public class FruitStatResponse {
    private long salesAmount;
    private long notSalesAmount;

    public void setStat(FruitStat stat) {
        if (stat.getSoldYn().equals("Y")) {
            this.salesAmount = stat.getAmount();
        } else {
            this.notSalesAmount = stat.getAmount();
        }
    }

    public long getSalesAmount() {
        return salesAmount;
    }

    public long getNotSalesAmount() {
        return notSalesAmount;
    }
}

댓글을 작성해보세요.

채널톡 아이콘