주제
JPA라는 개념을 배우고 유저 테이블에 JPA를 적용해봤다.
이제 JPA 연습해보자.
주요 내용
키워드
JPA
JPA 적용 및 연습
문제1
create table fruit
(
id bigint auto_increment,
name varchar(20),
warehousing_date date,
price int,
status ENUM('SOLD' , 'NOT_SOLD') DEFAULT 'NOT_SOLD',
primary key (id)
);
SQL
복사
warehousingDate에서 warehousing_date 으로 변경됨.
Hibernate는 자바 필드명에서 카멜 케이스(warehousingDate)를 스네이크 케이스(warehousing_date)로 자동 변환해서 변경했음.
혹시해서 테이블 컬럼명이 warehousingDate 이거 였을때
@Column(name = "warehousingDate", nullable = false)
private LocalDate warehousingDate;
Java
복사
이렇게 강제로 맵핑해줘도 안먹음…ㅋㅋㅋ 그래서 테이블 드랍시키고 새로 컬럼명 변경한걸로 생성
Fruit
@Entity
@Getter
public class Fruit {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
@Column(nullable = false)
private String name;
@Column(nullable = false)
private long price;
@Column(nullable = false)
private LocalDate warehousingDate;
@Enumerated(EnumType.STRING)
@Column(nullable = false)
private Status status;
protected Fruit(){}
public Fruit(String name, LocalDate warehousingDate, long price) {
this.name = name;
this.price = price;
this.warehousingDate =warehousingDate;
this.status = Status.NOT_SOLD;
}
public void updateSoldStatus(){
this.status = Status.SOLD;
}
public enum Status {
SOLD, NOT_SOLD
}
}
Java
복사
FruitService
@Service
public class FruitService {
private final FruitARepository fruitRepository;
public FruitService(FruitARepository fruitRepository) {
this.fruitRepository = fruitRepository;
}
public void saveFruit(FruitRequest request) {
fruitRepository.save(new Fruit(request.getName(), request.getWarehousingDate(), request.getPrice()));
}
public void updateFruit(FruitRequest request) {
Fruit fruit = fruitRepository.findById(request.getId())
.orElseThrow(IllegalArgumentException::new);
fruit.updateSoldStatus();
fruitRepository.save(fruit);
}
public FruitResponse getFruitStatus(String name) {
long salesAmount = fruitRepository.findAllByNameAndStatus(name, Fruit.Status.SOLD).stream()
.mapToLong(Fruit::getPrice)
.sum();
long notSalesAmount = fruitRepository.findAllByNameAndStatus(name, Fruit.Status.NOT_SOLD).stream()
.mapToLong(Fruit::getPrice)
.sum();
return new FruitResponse(salesAmount, notSalesAmount);
}
}
Java
복사
FruitRepository
public interface FruitRepository extends JpaRepository<Fruit, Long> {
Optional<Fruit> findByName(String name);
List<Fruit> findAllByNameAndStatus(String name, Fruit.Status status);
}
Java
복사
문제2
FruitCountResponse
@Getter
public class FruitCountResponse {
private long count;
public FruitCountResponse(long count) {
this.count = count;
}
}
Java
복사
FruitController
@GetMapping("/count")
public FruitCountResponse getFruitCount(@RequestParam String name) {
return fruitService.getFruitCount(name);
}
Java
복사
FruitService
public FruitCountResponse getFruitCount(String name) {
return new FruitCountResponse(fruitRepository.countByName(name));
}
Java
복사
FruitRepository
long countByName(String name);
Java
복사
문제3
FruitInfoResponse
@Getter
public class FruitInfoResponse {
private String name;
private Long price;
private LocalDate warehousingDate;
public FruitInfoResponse(String name, long price, LocalDate warehousingDate) {
this.name = name;
this.price = price;
this.warehousingDate =warehousingDate;
}
}
Java
복사
FruitController
@GetMapping("/list")
public List<FruitInfoResponse> getFruitsByPrice(@RequestParam String option, @RequestParam long price) {
return fruitService.getFruitsByPrice(option, price);
}
Java
복사
FruitService
public List<FruitInfoResponse> getFruitsByPrice(String option, long price) {
List<Fruit> fruits;
if (option.equals("GTE")) {
fruits = fruitRepository.findByPriceGreaterThanEqual(price);
} else if (option.equals("LTE")) {
fruits = fruitRepository.findByPriceLessThanEqual(price);
} else {
throw new IllegalArgumentException();
}
return fruits.stream()
.filter(fruit -> fruit.getStatus() == Fruit.Status.NOT_SOLD) // 판매되지 않은 상태를 확인한다.
.map(fruit -> new FruitInfoResponse(fruit.getName(), fruit.getPrice(), fruit.getWarehousingDate()))
.collect(Collectors.toList());
}
Java
복사
FruitRepository
List<Fruit> findByPriceGreaterThanEqual(long price);
List<Fruit> findByPriceLessThanEqual(long price);
Java
복사
참고
챗GPT