상품 도메인 개발

woom·2023년 4월 28일

Spring Boot

목록 보기
4/6
post-thumbnail

김영한 강사님 [실전! 스프링 부트와 JPA 활용1 - 웹 애플리케이션 개발] 강의 참조


🌼 구현 기능

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

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

  • 비즈니스 로직(Business logic) : 컴퓨터 프로그램에서 실세계의 규칙에 따라 데이터를 생성·표시·저장·변경하는 부분

  • 엔티티(데이터를 가지고 있는 곳)에서 비즈니스 로직을 작성하는 것이 응집도를 높여줌

    • ex. 상품을 주문할때 재고수량이 늘고 줄어드는 것을 item 엔티티 클래스에서 작성
package jpabook.jpashop.domain.item;

@Entity
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(name = "dtype")
@Getter @Setter
public abstract 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;
    }
}

📌 RuntimeException

  • 실행 중에 발생하며 시스템 환경적으로나 인풋 값이 잘못된 경우, 혹은 의도적으로 프로그래머가 잡아내기 위한 조건등에 부합할 때 발생(throw)되게 만든다.
package jpabook.jpashop.exception;

public class NotEnoughStockException extends RuntimeException {
    public NotEnoughStockException() {
        super();
    }

    //메세지 넘겨줌
    public NotEnoughStockException(String message) {
        super(message);
    }

    //메세지 + 문제가 발생한 근원 exception 넘겨줌
    public NotEnoughStockException(String message, Throwable cause) {
        super(message, cause);
    }

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

🌼 상품 리포지토리 개발

package jpabook.jpashop.repository;

import jpabook.jpashop.domain.item.Item;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Repository;

import javax.persistence.EntityManager;
import java.util.List;

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

📕 레포지토리 관련 개념

  • EntityManager.persist(entity) : entity를 영속성 컨텍스트에 저장하는 것(신규등록)

  • EntityManager.merge(entity) : 이미 DB에 저장되어 있는 것을 가져오는것 (update랑 비슷)


🌼 상품 서비스 개발

  • 상품 리포지토리에 단순히 위임만 하는 클래스
package jpabook.jpashop.service;


import jpabook.jpashop.domain.item.Item;
import jpabook.jpashop.repository.ItemRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

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

🌼 상품 기능 테스트


profile
Study Log 📂

0개의 댓글