-
[스프링부트/웹 애플리케이션 개발]상품 엔티티 개발스프링&스프링부트 2023. 1. 4. 23:39
구현기능 : 상품등록, 상품 목록 조회, 상품 수정
순서 : 상품 엔티티 개발(비즈니스 로직 추가) > 상품 리포지토리 개발 > 상품 서비스 개발 > 상품 기능 개발
상품 엔티티
@Entity @Inheritance(strategy = InheritanceType.SINGLE_TABLE) @DiscriminatorColumn(name="dtype") @Getter @Setter public abstract class Item { 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 realStock = this.stockQuantity - quantity; if (realStock < 0) { throw new NotEnoughStockException("need more stock"); } this.stockQuantity = realStock; } //@Setter 사용 대신 핵심비즈니스메서드(addStock, removeStock)를 이용해서 변경해야한다. //가장 객체지향적인 것 }
- 예외처리
> exception 패키지 생성 > NotEnoughStockException 클래스 생성
package jpabook.jpashop.exception; 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); } }
상품 리포지토리
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) { //item은 JPA 저장하기 전까지 id값이 없다 //id값이 없다 > 완전히 새로 생성하는 객체 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(); } }
상품 서비스
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> findItem() { return itemRepository.findAll(); } public Item findOne(Long itemId) { return itemRepository.findOne(itemId); } }
테스트코드는 직접 작성해 보기.
728x90'스프링&스프링부트' 카테고리의 다른 글
[스프링부트/웹 애플리케이션 개발]주문 도메인 개발-2 (0) 2023.01.05 [스프링부트/웹 애플리케이션 개발]주문 도메인 개발-1 (0) 2023.01.05 [스프링부트/웹 애플리케이션 개발]회원 기능 테스트 (0) 2023.01.04 [스프링부트/웹 애플리케이션 개발]회원 repository, 회원 service 개발, 인젝션 방법 3가지, @RequiredArgsConstructor (0) 2023.01.04 [스프링부트/웹 애플리케이션 개발]애플리케이션 아키텍처 (1) 2023.01.04