JPA/JPA 활용

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

chanhee01 2023. 7. 11. 18:09

item entity에 stockQuantity를 이용해서 수량을 계산하는 로직을 만든다.

// 비즈니스 로직 //
// 데이터를 가지고 있는 곳 쪽에 수량 비즈니스 로직이 있는 것이 객체지향 관점에서 좋다.

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

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

Service 계층에서 수량을 계산하고 set을 이용해서 수량을 체크할 수 있지만 첫 번째로 setter를 이용하는 것은 좋은 선택이 아니고 두 번째로 데이터를 가지고 있는 곳에서 비즈니스 로직을 계산하는 것이 효율적이다. 그렇기 때문에 Item entity에 stock을 계산하는 비즈니스 로직을 추가했다.

 

수량 추가는 그냥 +=로 quantity를 더해주었고, 감소는 수량이 0 이하로 내려갔을 때에는 NotEnoughStockException 에러를 발생시키게 했다.

 

 

NotEnoughStockException 예외

public class NotEnoughStockException extends RuntimeException {
    // extends 한 다음에 함수들 오버라이딩
    public NotEnoughStockException() {
        super();
    }

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

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

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