mojo's Blog

상품 도메인 개발 본문

Spring

상품 도메인 개발

_mojo_ 2022. 9. 2. 17:35

 

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

 

구현 기능

- 상품 등록

- 상품 목록 조회

- 상품 수정

 

구현 순서

 

  1. 상품 엔티티를 개발(비즈니스 로직 추가)
  2. 상품 리포지토리를 개발
  3. 상품 서비스를 개발
  4. 상품 기능을 테스트

 

@Entity
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(name = "dtype")
@Getter 
public abstract class Item {

	...

    /**
     * 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;
    }
}

 

Item 클래스에서 stock 을 추가하거나 제거할 수 있도록 메서드를 추가해주었다.

그러나 removeStock 메서드에서 제거하고 난 후의 나머지 stock 의 갯수가 음수가 될 경우에 예외를

반환해야 하는데 그에 대한 클래스는 다음과 같이 선언하였다.

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

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

 

 

상품 리포지토리 개발

 

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

 

save 메서드에서 상품의 id 가 없는 경우는 데이터베이스에 반영되지 않은 새로운 객체이다.

따라서 persist 하고 그 외에는 이미 등록되어진 상품이기 때문에 merge 를 적용한다.

 

 

상품 서비스 개발

 

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

 

우선 클래스 위에 @Transactional 에서 readOnly 를 true 로 한 다.

그리고 saveItem 메서드에서 insert 와 같은 삽입쿼리가 수행할 때, readOnly 가 false 가 되어야 하므로

@Transactional 을 달아준다.

 

'Spring' 카테고리의 다른 글

웹 계층 개발 - (1)  (2) 2022.09.06
주문 도메인 개발  (0) 2022.09.06
회원 도메인 개발  (1) 2022.09.02
애플리케이션 구현 준비  (2) 2022.09.02
도메인 분석 설계  (0) 2022.08.08
Comments