상품 도메인 개발
Reference : Inflearn 실전 스프링부트와 JPA 활용 1 (김영한님 강의)
상품 도메인 개발
상품 엔티티 개발
상품 등록, 상품 목록 조회, 상품 수정 기능을 포함한 상품 엔티티를 개발해보자.
//==비즈니스 로직==//
/**
* stock 증가
* */
public void addStack(int quantity){
this.sotckQuantity += quantity;
}
/**
* stock 감소
* */
public void removeStock(int quantity){
int restStock = this.sotckQuantity - quantity;
if(restStock<0){
throw new NotEnoughStockException("need more stock");
}
this.sotckQuantity = restStock;
}
Item.java에서 재고 증가, 감소하는 로직을 추가
data를 가지고 있는 쪽에 비즈니스 로직을 가지고 있는게 관리하기 좋다.
예외 추가 (NotEnoughStockException)
package jpabook.jpashop.exceptioin;
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);
}
}
ctrl+O 해서 RuntimeException Exception override
상품 리포지토리 개발
repository/ItemRepository.java
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();
}
}
item은 jpa에 저장하기 전까지 id값이 없다. 즉, 새로 생성한 객체.
따라서 em.persist로 신규 등록하기. update하는거라고 생각하자.
상품 서비스 개발
service/ItemService.java
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);
}
}
상품 서비스는 상품 리포지토리에 단순히 위임만 하는 클래스이다.
Last updated