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)
728x90
'Spring' 카테고리의 다른 글
[인프런 워밍업 클럽] 미니프로젝트 1단계 (0) | 2024.03.04 |
---|---|
[인프런 워밍업 클럽] BE - 2주차 회고록 (0) | 2024.03.03 |
[인프런 워밍업 클럽] BE 6번째 과제 - Controller - Service - Repository로 분리하기 (0) | 2024.02.26 |
[인프런 워밍업 클럽] BE - 1주차 회고록 (0) | 2024.02.25 |
[인프런 워밍업 클럽] BE 5번째 과제 - 클린 코드 (0) | 2024.02.23 |