[실전! 스프링 부트와 JPA 활용1 - 웹 애플리케이션 개발] 05. 상품 도메인 개발

Turtle·2024년 7월 4일
0
post-thumbnail

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

@Entity
@Getter
@Setter
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn
public abstract class Item {
	@Id
	@GeneratedValue
	private Long id;

	@ManyToMany(mappedBy = "items")
	private List<Category> categories = new ArrayList<>();

	private String name;
	private int price;
	private int stockQuantity;

	// 재고 수량 증가
	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;
	}
}
  • ✔️예외 클래스 추가(재고 관리 예외)
    • 예외도 하나의 객체다.
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);
	}
}

🙄상품 리포지토리 개발

@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 as 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> findItems() {
		return itemRepository.findAll();
	}

	public Item findOne(Long itemId) {
		return itemRepository.findOne(itemId);
	}
}

0개의 댓글