[인프런 워밍업 클럽_0기] BE 일곱 번째 과제 (진도표 7일차)

2024. 2. 27. 21:36·공부/인프런 워밍업 클럽_BE
반응형

 

이미지를 클릭하면 해당 페이지로 이동합니다.

 

강의 출처

 

자바와 스프링 부트로 생애 최초 서버 만들기, 누구나 쉽게 개발부터 배포까지! [서버 개발 올인

Java와 Spring Boot, JPA, MySQL, AWS를 이용해 서버를 개발하고 배포합니다. 웹 애플리케이션을 개발하며 서버 개발에 필요한 배경지식과 이론, 다양한 기술들을 모두 학습할 뿐 아니라, 다양한 옵션들

www.inflearn.com

 

진도표 7일차와 연결됩니다
우리는 JPA라는 개념을 배우고 유저 테이블에 JPA를 적용해 보았습니다. 몇 가지 문제를 통해 JPA를 연습해 봅시다! 🔥

 

문제 1

과제 #6 에서 만들었던 Fruit 기능들을 JPA를 이용하도록 변경해보세요!

Fruit 클래스 변경

@Entity
public class Fruit {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    
    @Column(nullable = false, length = 25)
    private String name;
    private long price;
    private LocalDate warehousingDate;
    @ColumnDefault("0")
    private int salesYN;

    protected Fruit() {
    }

    public Fruit(long id, String name, long price, LocalDate warehousingDate) {
        this.id = id;
        this.name = name;
        this.price = price;
        this.warehousingDate = warehousingDate;
    }

    public Fruit(long id, String name, long price, LocalDate warehousingDate, int salesYN) {
        this.id = id;
        this.name = name;
        this.price = price;
        this.warehousingDate = warehousingDate;
        this.salesYN = salesYN;
    }

    public long getId() {
        return id;
    }

    public String getName() {
        return name;
    }

    public long getPrice() {
        return price;
    }

    public LocalDate getWarehousingDate() {
        return warehousingDate;
    }

    public int getSalesYN() {
        return salesYN;
    }

    public void setSalesYN() {
        this.salesYN = 1;
    }
}

 

FruitRepository 생성

public interface FruitRepository extends JpaRepository<Fruit, Long> {
    List<Fruit> findAllByNameAndSalesYN(String name, int salesYn);
}

 

FruitService 수정

@Service
public class FruitService {

    private final FruitRepository fruitRepository;

    public FruitService(FruitRepository fruitRepository) {
        this.fruitRepository = fruitRepository;
    }

    public void save(FruitSaveRequest request) {
        fruitRepository.save(new Fruit(request.getName(), request.getPrice(), request.getWarehousingDate()));
    }

    public void update(long id) {
        Fruit fruit = fruitRepository.findById(id)
                .orElseThrow(IllegalArgumentException::new);
        fruit.setSalesYN();
        fruitRepository.save(fruit);
    }

    public FruitStatResponse fruitStat(String name) {
        List<Fruit> salesList = fruitRepository.findAllByNameAndSalesYN(name, 1);
        List<Fruit> notSalesList = fruitRepository.findAllByNameAndSalesYN(name, 0);

        long salesAmount = 0;
        long notSalesAmount = 0;

        for (Fruit fruit : salesList) {
            salesAmount += fruit.getPrice();
        }

        for(Fruit fruit : notSalesList) {
            notSalesAmount += fruit.getPrice();
        }

        return new FruitStatResponse(salesAmount, notSalesAmount);
    }
}

 

 

문제 2

우리는 특정 과일을 기준으로 지금까지 우리 가게를 거쳐갔던 과일 개수를 세고 싶습니다.
<문제 1>에서 만들었던 과일 Entity Class를 이용해 기능을 만들어 보세요!

예를 들어
1. (1, 사과, 3000원, 판매 O)
2. (2, 바나나, 4000원, 판매 X)
3. (3, 사과, 3000원, 판매 O)
와 같은 세 데이터가 있고, 사과를 기준으로 과일 개수를 센다면, 우리의 API는 2를 반환할 것입니다.

Controller

@GetMapping("/count")
public FruitCountResponse getCount(@RequestParam String name) {
    return fruitService.getCount(name);
}

 

DTO

public class FruitCountResponse {

    private long count;

    public FruitCountResponse() {}

    public FruitCountResponse(long count) {
        this.count = count;
    }

    public long getCount() {
        return count;
    }
}

 

Service

public FruitCountResponse getCount(String name) {
    return new FruitCountResponse(fruitRepository.countByName(name));
}

 

Repository

int countByName(String name);

 

포스트맨 테스트

 

 

문제 3

우리는 아직 판매되지 않은 특정 금액 이상 혹은 특정 금액 이하의 과일 목록을 받아보고 싶습니다.
구체적인 스펙은 다음과 같습니다.

 

DTO

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

    public FruitListResponse(String name, long price, LocalDate warehousingDate) {
        this.name = name;
        this.price = price;
        this.warehousingDate = warehousingDate;
    }

    public String getName() {
        return name;
    }

    public long getPrice() {
        return price;
    }

    public LocalDate getWarehousingDate() {
        return warehousingDate;
    }
}

 

Controller

@GetMapping("list")
public List<FruitListResponse> getList(@RequestParam String option, @RequestParam long price)  {
    return fruitService.getList(option, price);
}

 

Service

public List<FruitListResponse> getList(String option, long price) {
    Optional<List<FruitListResponse>> list;

    if(option.equals("GTE")) {
        list = fruitRepository.findAllByPriceGreaterThanEqual(price);
    }
    else {
        list = fruitRepository.findAllByPriceLessThanEqual(price);
    }
    return list.orElseThrow(IllegalArgumentException::new);
}

 

Repository

Optional<List<FruitListResponse>> findAllByPriceGreaterThanEqual(long price);
Optional<List<FruitListResponse>> findAllByPriceLessThanEqual(long price);

 

포스트맨 테스트

 

반응형
저작자표시 비영리 변경금지 (새창열림)
'공부/인프런 워밍업 클럽_BE' 카테고리의 다른 글
  • [인프런 워밍업 클럽_0기] BE 미니 프로젝트 1단계
  • [인프런 워밍업 클럽_0기] BE 미니 프로젝트 가이드 (진도표 8일차 시작)
  • [인프런 워밍업 클럽_0기] BE 여섯 번째 과제 (진도표 6일차)
  • [인프런 워밍업 클럽_0기] BE 다섯 번째 과제 (진도표 5일차)
데부한
데부한
어차피 할 거면 긍정적으로 하고 싶은 개발자
    반응형
  • 데부한
    동동이개발바닥
    데부한
  • 전체
    오늘
    어제
    • 분류 전체보기 (307)
      • 방통대 컴퓨터과학과 (27)
        • 잡담 (9)
        • 3학년1학기 (17)
      • 프로젝트 및 컨퍼런스 회고 (1)
        • 프로젝트 (4)
        • 한이음 프로젝트 (0)
        • 회고 (3)
      • 공부 (165)
        • Spring (37)
        • JPA (71)
        • 인프런 워밍업 클럽_BE (10)
        • Java (6)
        • React.js (27)
        • 넥사크로 (11)
        • 기타 (3)
      • 알고리즘 (85)
        • 알고리즘 유형 (10)
        • 알고리즘 풀이 (57)
        • SQL 풀이 (18)
      • 에러 해결 (13)
      • 잡담 (7)
        • 국비교육 (2)
        • 구매후기 (5)
        • 진짜 잡담 (0)
  • 블로그 메뉴

    • Github
    • Linkedin
    • 홈
    • 방명록
    • 글쓰기
    • 관리
  • 링크

  • 공지사항

  • 인기 글

  • 태그

    백준
    RESTful
    springboot
    react
    자바스크립트
    QueryDSL
    oracle
    코딩테스트
    기출문제
    토비의스프링부트
    스프링부트
    SQL
    egov
    SpringBoot를 이용한 RESTful Web Service 개발
    운영체제
    Java
    JPA
    넥사크로
    알고리즘
    방통대
    토이프로젝트
    개발자
    Spring
    IT
    프로그래머스
    MSA
    전자정부프레임워크
    인프런
    프론트엔드
    에러해결
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.3
데부한
[인프런 워밍업 클럽_0기] BE 일곱 번째 과제 (진도표 7일차)
상단으로

티스토리툴바