springboot

[springboot] 실전! 스프링부트와 JPA 활용 - 3. 상품 도메인(Item)

힝뿌 2023. 11. 14. 00:10
반응형

저번에 이어 이번에는 상품 도메인 개발을 해볼 예정이다.

 

 

 

 

상품 도메인 개발

구현 기능

  • 상품 등록
  • 상품 목록 조회
  • 상품 수정

 

순서

  • 상품 엔티티 개발(비즈니스 로직 추가)
  • 상품 리포지토리 개발
  • 상품 서비스 개발
  • 상품 기능 테스트

 

 

 

상품 엔티티 개발(비즈니스 로직 추가)

상품 엔티티 코드

상품의 수량을 추가하고 빼는 로직을 추가했다.

@Entity
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(name = "dtype")
@Getter
@Setter
public class Item {             // 상품 엔티티

    @Id
    @GeneratedValue
    @Column(name = "item_id")
    private Long id;

    private String name;

    private int price;

    private int stockQuantity;

    @ManyToMany(mappedBy = "items")
    private List<Category> categories = new ArrayList<>();

    // == 비즈니스 로직 == //
    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;
    }
}
  • addStock() 메서드는 파라미터로 넘어온 수만큼 재고를 늘란다. 이 메서드는 중가 하거나 주문을 취소해서 재고를 다시 늘려야 할 때 사용한다.
  • removeStock() 메서드는 파라미터로 넘어온 수 만큼 재고를 줄인다. 만약 재고가 부족하면 예외가 발생한다. 주로 상품을 주문할 때 사용한다.

 

 

 

 

예외 추가

public class NotEnoughStockException extends RuntimeException {

    public NotEnoughStockException() {
    }

    public NotEnoughStockException(String message) {
        super(message);
    }

    public NotEnoughStockException(String message, Throwable cause) {
        super(message, cause);
    }

    public NotEnoughStockException(Throwable cause) {
        super(cause);
    }

}
  • RuntimeException
    • 비체크 예외의 일종
      • 비체크 예외란?
      • 컴파일러가 예외 처리를 강제하지 않기 때문에 명시적으로 처리하지 않아도 되는 예외들을 의미한다. 즉, 코드에서 예외처리를 하지 않아도 컴파일이 가능하다.
      • 주요 하위 클래스들로는 아래와 같은 클래스들이 있다.
        • NullPointerException : 객체 참조가 없는 상태에서 메서드를 호출할 때 발생한다.
        • IndexOutOfBoundsException : 배열이나 컬렉션에서 유효하지 않은 인텍스로 접근할 때 발생한다.
        • IllegalArgumentException : 메서드에서 잘못된 인수가 전달될 때 발생한다.
        • 기타 등등

 

 

 

 

상품 Repository 개발

상품 repository 코드

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

 

 

 

 

 

 

상품 서비스 개발

상품 서비스 코드

상품 서비스는 상품 Repository에 단순히 위임만 하는 클래스다.

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

 

 

 

 

 

상품 기능 테스트

상품 테스트는 회원 테스트와 비슷하므로 생략한다고 적혀있지만, 마지막에 한 번 구현해보려고 한다.

 

 

 

 

 

지난번 회원을 구현할 때와는 달리 상품 기능을 구현하는 부분이 많지 않아 빠르게 넘어갈 수 있는 듯하다.

다음번에는 주문 도메인 개발을 기록해 볼 예정이다.

반응형