[인프런 워밍업 클럽 스터디 1기 과제 #7] JPA 적용

qk·2024년 5월 16일
post-thumbnail

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

문제 1

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

@Entity
public class Fruit {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private long id;

    @Column(length = 25)
    private String name;

    @Column(name="warehousing_date")
    private LocalDate warehousingDate;

    @Column
    private long price;

    @Column
    private char sold;

    protected Fruit(){
    }

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

    public long getId() {
        return id;
    }

    public String getName() {
        return name;
    }

    public long getPrice() {
        return price;
    }

    public void updateSold() {
        this.sold = 'Y';
    }
}

FruitService.java

@Service
public class FruitService {

    private final FruitJpaRepository fruitRepository;

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

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

    public void updateFruit(FruitUpdateRequest request){
       Fruit fruit = fruitRepository.findById(request.getId()).orElseThrow(IllegalArgumentException::new);
       fruit.updateSold();
       fruitRepository.save(fruit);
    }

    public FruitResponse saleState(String name){
        long salesAmount = fruitRepository.findAllByNameAndSold(name, 'Y').stream()
                .mapToLong(Fruit::getPrice).sum();;
        long notSalesAmount = fruitRepository.findAllByNameAndSold(name, 'N').stream()
                .mapToLong(Fruit::getPrice).sum();;
        return new FruitResponse(salesAmount, notSalesAmount);
    }
}

FruitJpaRepository.java

public interface FruitJpaRepository extends JpaRepository<Fruit, Long> {
    List<Fruit> findAllByNameAndSold(String name, char sold);
}

문제 2

FruitCountResponse.java

public class FruitCountResponse {
    private long count;

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

    public long getCount() {
        return count;
    }
}

FruitController.java

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

FruitService.java

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

FruitJpaRepository.java

long countByName(String name);

문제 3

FruitListResponse.java

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

    public String getName() {
        return name;
    }

    public Long getPrice() {
        return price;
    }

    public LocalDate getWarehousingDate() {
        return warehousingDate;
    }

FruitController.java

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

FruitService.java

public List<FruitListResponse> getFruitsByPrice(String option, long price) {
        List<Fruit> fruits;

        if (option.equals("GTE")) {
            fruits = fruitRepository.findAllByPriceGreaterThanEqual(price);
        } else if (option.equals("LTE")) {
            fruits = fruitRepository.findAllByPriceLessThanEqual(price);
        } else {
            throw new IllegalArgumentException();
        }

        return fruits.stream()
                .filter(fruit -> fruit.getSold() == 'N')
                .map(fruit -> new FruitListResponse(fruit.getName(), fruit.getPrice(), fruit.getWarehousingDate()))
                .collect(Collectors.toList());
}

FruitJpaRepository.java

List<Fruit> findAllByPriceGreaterThanEqual(long price);
List<Fruit> findAllByPriceLessThanEqual(long price);

출처

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

0개의 댓글