[스프링 활용] 상품 도메인 , 리포지토리 , 서비스 개발

atdawn·2024년 6월 7일

SPRING BOOT+JPA

목록 보기
24/49

참고 : 인프런 [ 실전! 스프링 부트와 JPA 활용1 - 웹 애플리케이션 개발 - 김영한 ]


상품 도메인

이번에는 상품 엔티티 자체에 비즈니스 로직을 추가해보자. (도메인 주도 설계)
-> 객체 지향적

~/domain/Item.java

...
//==비즈니스 로직//

    /**
     * stock 증가
     */
    public void addStock(int qauntity){
        this.stockQuantity+=qauntity;
    }

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

Item 엔티티가 StockQauntity 정보를 가지고 있기 때문에, 엔티티 자체에서 비즈니스 로직을 다루는 것이 좋다.


상품의 재고가 0개 이하일때 발생하는 익셉션을 생성해보자.

~/exception/NotEnoughStockException.java

public class NotEnoughStockException extends RuntimeException {

    public NotEnoughStockException() {
        super();
    }

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

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

    protected NotEnoughStockException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
        super(message, cause, enableSuppression, writableStackTrace);
    }

    public NotEnoughStockException(String need_more_stock) {
    }
}

NotEnoughStockException은 RuntimeException을 extends 하고, 오버라이드 해준다.


상품 리포지토리

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){
      ...
    }

    public List<Item> findAll(){
      ...
    }
}
  • 아이템의 id가 없으면 (처음 저장하는 아이템) persist로 item 을 저장해준다. (id생성)
    - merge : 추후 수업 예정

상품 서비스

@Service
@Transactional(readOnly = true) //기본값
@RequiredArgsConstructor
public class ItemService {

    private final ItemRepository itemRepository;

    @Transactional //readOnly=false
    public void saveItem(Item item){
      ...
    }

    public List<Item> findItems(){
       ...
    }

    public Item findOne(Long itemId){
        ...
    }
}
  • 상품 서비스는 상품리파지토리에 단순하게 위임만 하는 클래스.
  • 이러한 서비스 클래스를 작성하지 않고 컨트롤러에서 바로 아이템 리파지토리에 접근하는 것도 크게 문제 X
profile
복습 복습 복습

0개의 댓글