본문 바로가기
Study/실전! 스프링 부트와 JPA 활용1

주문 개발 1 (Item - 상품 개발)

by Subi 2022. 7. 14.

이제 핵심로직인 주문을 개발한다.

 

제일처음으로 한 것은 Item 엔티티에 재고 증가와 재고 감소에 대한 메서드를 만들어주는 것이다.

- 재고 증가

   public void addStock(int quantity){
        this.stockQuantity += quantity;
    }

 

- 재고 감소

 public void removeStock(int quantity){
        int restStock = this.stockQuantity - quantity;
        if(restStock < 0){
            throw new NotEnoughStockException("need more stock");
        }
        this.stockQuantity = restStock;
    }

 

재고 증가와 재고 감소는 현재 객체로 받은 재고에서 변동이 생기는 quantity 변수를 더하고 빼주는 메서드로 작업했다.

재고 증가는 간단한 + 로직이지만 재고 감소는 0 보다 작은값이 되면 안되므로, NotEnoughStockException 라는 예외처리 Class를 만들어 따로 예외에 대한 처리를 진행하였다.

-Exception Class 

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

Item 엔티티에서의 작업을 한 후

 

ItemRepository를 만들어 작업을 진행 하였다.

@Repository
@RequiredArgsConstructor
public class ItemRepository {

    private final EntityManager em;

    public void save(Item item){
        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(){
        return em.createQuery("select i from Item i", Item.class).getResultList();
    }

}

ItemRepository는 

저장을 하는 save 메서드, 하나의 상품을 검색하는 findOne 메서드 , 전체 상품을 검색하는 findAll 메서드를 만들었다.

 

그 다음 ItemRepository를 수행하는

ItemService 클래스를 만들었다.

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

}

 

강의 : 인프런 실전! 스프링 부트와 JPA 활용1 (김영한)  https://inf.run/VMWU

'Study > 실전! 스프링 부트와 JPA 활용1' 카테고리의 다른 글

주문 개발 3 (OrderService- 주문 개발)  (0) 2022.07.15
주문 개발 2 (Order- 주문 개발)  (0) 2022.07.14
회원 기능 테스트  (0) 2022.07.12
회원 서비스 개발  (0) 2022.07.12
회원 Repository  (0) 2022.07.11

댓글