본문 바로가기

Spring

[인프런 워밍업 클럽] 7번째 과제 - JPA 사용하기

728x90

 

 

🔑문제 1

과제 6은 아래 링크에서 확인 할 수 있다.
https://yestruly.tistory.com/96

 

🔑코드

  • Entity
package com.group.libraryapp.domain.fruit;

import java.time.LocalDate;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

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

  @Column
  private String name;

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

  @Column
  private Long price;

  @Column(name = "is_sell")
  private boolean isSell;

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

  protected Fruit(){}

  public void updateSellStatus() {
    this.isSell = true;
  }

  public Long getPrice(){
    return this.price;
  }
}

 

  • Controller
package com.group.libraryapp.controller.fruit;

import com.group.libraryapp.dto.fruit.request.FruitRequest;
import com.group.libraryapp.dto.fruit.request.FruitUpdateRequest;
import com.group.libraryapp.dto.fruit.response.FruitPriceResponse;
import com.group.libraryapp.service.fruit.FruitJpaService;
import com.group.libraryapp.service.fruit.FruitService;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

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

  private final FruitJpaService fruitService;

  public FruitController(FruitJpaService fruitService) {
    this.fruitService = fruitService;
  }


  @PostMapping("")
  public void registerFruit(@RequestBody FruitRequest request) {
   fruitService.registerFruit(request);
  }

  @PutMapping("")
  public void updateFruit(@RequestBody FruitUpdateRequest request) {
    fruitService.updateFruit(request);
  }

  @GetMapping("/stat")
  public FruitPriceResponse getFruitSellPrice(@RequestParam String name) {
     return fruitService.getFruitSellPrice(name);
  }

}

 

  • Service
package com.group.libraryapp.service.fruit;

import com.group.libraryapp.domain.fruit.Fruit;
import com.group.libraryapp.dto.fruit.request.FruitRequest;
import com.group.libraryapp.dto.fruit.request.FruitUpdateRequest;
import com.group.libraryapp.dto.fruit.response.FruitPriceResponse;
import com.group.libraryapp.repository.fruit.FruitJpaRepository;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class FruitJpaService {
  private final FruitJpaRepository fruitRepository;

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

  @Transactional
  public void registerFruit(FruitRequest request) {
    fruitRepository.save(new Fruit(request.getName(), request.getWarehousingDate(), request.getPrice()));
  }

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

    fruit.updateSellStatus();
  }

  @Transactional
  public FruitPriceResponse getFruitSellPrice(String name) {
    Long salesAmount = fruitRepository.findByNameAndIsSell(name, true)
        .stream().mapToLong(fruits -> fruits.getPrice()).sum();
    Long notSalesAmount = fruitRepository.findByNameAndIsSell(name, false)
        .stream().mapToLong(fruits -> fruits.getPrice()).sum();

    return new FruitPriceResponse(salesAmount, notSalesAmount);
  }
}

 

  • Repository
package com.group.libraryapp.repository.fruit;

import com.group.libraryapp.domain.fruit.Fruit;
import java.util.List;
import java.util.Optional;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

@Repository
public interface FruitJpaRepository extends JpaRepository<Fruit, Long> {
  Optional<Fruit> findById(Long id);
  List<Fruit>  findByNameAndIsSell(String name, boolean isSell);
}

 


 

🔑문제 2

 

 

🔑코드

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

 

  • 응답 DTO
package com.group.libraryapp.dto.fruit.response;

public class FruitCountResponse {

  public Long getCount() {
    return count;
  }

  private final Long count;


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

 

  • Service
 public FruitCountResponse getFruitCount(String name) {
    Long count = fruitRepository.countByName(name);
    return new FruitCountResponse(count);
  }

 

  • Repository
Long countByName(String name);

 

  • Postman 테스트 결과

 

현재 데이터베이스에는 사과 데이터가 3개, 딸기 데이터가 2개 등록되어있다.
사과의 개수를 출력하면 count : 3이 반환되면 성공!!

 

 

결과가 잘 반환된 걸 확인할 수 있다.

 

 


 

🔑문제 3

 

 

🔑코드

  • Controller
@GetMapping("/list")
  public ResponseEntity<List<FruitListResponse>> getFruitList(@RequestParam String option, @RequestParam Long price){
    List<FruitListResponse> fruits = fruitService.getFruitList(option, price);
    return ResponseEntity.ok(fruits);

  }

 

  • 응답 DTO
package com.group.libraryapp.dto.fruit.response;

import com.group.libraryapp.domain.fruit.Fruit;
import java.time.LocalDate;

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

  public FruitListResponse(Fruit fruit) {
    this.name = fruit.getName();
    this.price = fruit.getPrice();
    this.warehousingDate = fruit.getWarehousingDate();
  }

  public FruitListResponse() {
  }

  public String getName() {
    return name;
  }

  public Long getPrice() {
    return price;
  }

  public LocalDate getWarehousingDate() {
    return warehousingDate;
  }

}

 

  • Service
 public List<FruitListResponse> getFruitList(String option, Long price) {
    List<Fruit> fruits;
    if ("GTE".equals(option)) {
      fruits = fruitRepository.findAllByPriceGreaterThanEqualAndIsSellIsFalse(price);
    } else if ("LTE".equals(option)) {
      fruits = fruitRepository.findAllByPriceLessThanEqualAndIsSellIsFalse(price);
    } else {
      throw new IllegalArgumentException();
    }
    return fruits.stream()
        .map(FruitListResponse::new)
        .collect(Collectors.toList());
  }

 

  • Repository
  List<Fruit> findAllByPriceGreaterThanEqualAndIsSellIsFalse(Long price);
  List<Fruit> findAllByPriceLessThanEqualAndIsSellIsFalse(Long price);

 

  • Postman 테스트 결과

데이터베이스에는 위와 같이 데이터가 저장되어있다.

 

 

결과가 잘 반환되는 걸 확인할 수 있다.

 

 

 

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

 

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

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

www.inflearn.com

 

728x90