📌 구현 기능
- 상품 등록
- 상품 목록 조회
- 상품 수정
📌 순서
1️⃣ 상품 엔티티 개발(비즈니스 로직 추가)
2️⃣ 상품 리포지토리 개발
3️⃣ 상품 서비스 개발
4️⃣ 상품 기능 테스트 (간단해서 생략함)
// ==비즈니스 로직== //
/**
* stock 증가
*/
public void addStock(int quantity) {
this.stockQuantity += quantity;
}
/**
* stock 감소
*/
public void removeStock(int quantity) {
int restStock = this.stockQuantity - quantity;
if (restStock < 0) {
// 새로운 exception 생성
throw new NotEnoughStockException("need more stock");
}
this.stockQuantity = restStock;
}
addStock()
메서드는 파라미터로 넘어온 수만큼 재고를 늘린다.removeStock()
메서드는 파라미터로 넘어온 수만큼 재고를 줄인다.package jpabook.jpashop.exception;
public class NotEnoughStockException extends RuntimeException {
public NotEnoughStockException() {
super();
}
public NotEnoughStockException(String message) {
super(message);
}
public NotEnoughStockException(String message, Throwable cause) {
super(message, cause);
}
public NotEnoughStockException(Throwable cause) {
super(cause);
}
}
package jpabook.jpashop.repository;
import jpabook.jpashop.domain.item.Item;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Repository;
import javax.persistence.EntityManager;
import java.util.List;
@Repository
@RequiredArgsConstructor
public class ItemRepository {
private final EntityManager em;
public void save(Item item) {
// 처음 저장할 때는 아이템의 id가 존재하지 않으므로 이 부분을 고려해야 함
if (item.getId() == null) {
// 아이템 그냥 저장
em.persist(item);
} else {
// 아이템 업데이트(?) - 나중에 자세히 배움
em.merge(item);
}
}
public Item findOne(Long id) {
return em.find(Item.class, id);
}
public List<Item> findAll() {
// 여러 개 찾는 것은 JPQL을 작성해야 함
return em.createQuery("select i from Item i", Item.class)
.getResultList();
}
}
save()
persist()
실행merge()
를 실행 package jpabook.jpashop.service;
import jpabook.jpashop.domain.item.Item;
import jpabook.jpashop.repository.ItemRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
@Service
@Transactional(readOnly = true)
@RequiredArgsConstructor
public class ItemService {
private final ItemRepository itemRepository;
@Transactional
public void saveItem(Item item) {
itemRepository.save(item);
}
public List<Item> findItems() {
return itemRepository.findAll();
}
public Item findOne(Long itemId) {
return itemRepository.findOne(itemId);
}
}