[인프런 BE 0기] JPA를 이용한 기능 개발

HeeYeon Kim·2024년 2월 27일
0

스터디

목록 보기
7/8
post-thumbnail

인프런 워밍업 클럽 스터디 0기
BE 7일차



문제1

Fruit 기능들을 JPA를 이용하도록 변경


Fruit

import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import lombok.Getter;
import lombok.NoArgsConstructor;

import java.time.LocalDate;

@Getter
@Entity(name="fruit")
@NoArgsConstructor
public class Fruit {
    @Id @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String name;
    private LocalDate warehousingDate;
    private long price;
    private boolean isSold;

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

    public void updateIsSold(){
      this.isSold = true;
   }
}
  • @Entity : 엔티티
  • @NoArgsConstructor : 인자 없는 생성자 생성
  • @Id, @GeneratedValue : 테이블 Primary key 설정, auto_increment 설정

FruitRepository

import com.group.libraryapp.domain.Fruit;
import org.springframework.data.jpa.repository.JpaRepository;

import java.util.List;

public interface FruitRepository extends JpaRepository<Fruit,Long> {
    List<Fruit> findByNameAndIsSold(String name,boolean isSold);
}
  • JpaRepository 상속
  • findByNameAndIsSold : 이름과 isSold 여부에 따라 리스트를 반환하는 메소드 생성

FruitService

  • saveFruit

    //FruitService 클래스
    public void saveFruit(Fruit fruit){
       fruitRepository.save(fruit);
    }

  • sellFruit : 과일 판매 시 판매 여부 true로 변경

    //fruitService 클래스 
    public void sellFruit(long id){
         String sql = "UPDATE fruit SET isSold=1 WHERE id=?";
         Fruit fruit = fruitRepository.findById(id)
                         .orElseThrow();
         fruit.updateIsSold();
         fruitRepository.save(fruit);
     }
    //fruit 클래스
    public void updateIsSold(){
         this.isSold = true;
     }

  • calcPrice : 특정 과일의 팔린 금액, 팔리지 않은 금액 조회

    public FruitResponse calcPrice(String name){
    
         long salesAmount = fruitRepository.findByNameAndIsSold(name,true)
                 .stream().mapToLong(fruit->fruit.getPrice()).sum();
         long notSalesAmount = fruitRepository.findByNameAndIsSold(name,false)
                 .stream().mapToLong(fruit->fruit.getPrice()).sum();
    
         return new FruitResponse(salesAmount,notSalesAmount);
     }
    • findByNameAndIsSold 메소드 이용해 이름, 판매 여부를 기준으로 과일 리스트를 가져온 다음 stream 메소드를 이용해 합 계산
    • FruitResponse 클래스 이용해 JSON 반환

결과

  • fruit 정보 저장

  • 팔린 과일 표시

  • 사과 팔린 금액과 팔리지 않은 금액 조회




문제2

특정 과일 기준 가게를 거쳐갔던 과일의 개수 세는 기능 개발

FruitController

@GetMapping("/api/v1/fruit/count")
public FruitCountResponse countFruit(@RequestParam String name){
    return fruitService.countFruit(name);
}

FruitCountResponse

import lombok.Getter;

@Getter
public class FruitCountResponse {
    private long count;

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

FriutService

public FruitCountResponse countFruit(String name){
        long count = fruitRepository.findAllByName(name).stream().count();
        return new FruitCountResponse(count);
}

FruitRepository 메소드 추가

List<Fruit> findAllByName(String name);

결과




문제3

판매되지 않은 특정 금액 이상 혹은 특정 금액 이하의 과일 목록 조회 기능 개발

FruitController

@GetMapping("/api/v1/fruit/list")
public List<FruitListResponse> returnFruitList(@RequestParam String option, long price){
        return fruitService.returnFruitList(option,price);
}

FruitListResponse

import lombok.Getter;

import java.time.LocalDate;

@Getter
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;
    }
}

FruitService

public List<FruitListResponse> returnFruitList(String option, long price){

        if(option.equals("GTE")){
            return fruitRepository.findAllByPriceGreaterThanEqualAndIsSold(price,false)
                    .stream().map(fruit-> new FruitListResponse(fruit.getName(),fruit.getPrice(),fruit.getWarehousingDate()))
                    .collect(Collectors.toList());

        }else{
            return fruitRepository.findAllByPriceLessThanEqualAndIsSold(price,false)
                    .stream().map(fruit-> new FruitListResponse(fruit.getName(),fruit.getPrice(),fruit.getWarehousingDate()))
                    .collect(Collectors.toList());
        }
    }

FruitRepository 메소드 추가

List<Fruit> findAllByPriceGreaterThanEqualAndIsSold(long price,boolean isSold);
List<Fruit> findAllByPriceLessThanEqualAndIsSold(long price,boolean isSold);

결과

  • 현재 Fruit 데이터베이스

  • Option=GTE&price=3000

  • Option=LTE&price=3000





강의

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

0개의 댓글