[구현 기능]
- 상품 등록
- 상품 목록 조회
- 상품 수정
package jpabook.jpashop.domain;
import jakarta.persistence.*;
import jpabook.jpashop.exception.NotEnoughStockException;
import lombok.Getter;
import lombok.Setter;
import java.util.ArrayList;
import java.util.List;
@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> items = 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;
}
}
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);
}
}
addStock()
removeStock()
package jpabook.jpashop.repository;
import jakarta.persistence.EntityManager;
import jpabook.jpashop.domain.Item;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Repository;
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();
}
}
save() - persist or merge
저장하고자 하는 item의 id 값 존재 여부 확인
id 값이 없으면 신규로 보고 persist()
실행
id 값이 있으면 수정으로 보고 merge()
실행
persist()
merge()
persist
상태였다가 detached
된 상태에서, 그 다음에 Managed
상태가 될 때 merge
한다고 함엔티티 생명주기 정리
https://velog.io/@syb0228/Entity-LifeCycle
package jpabook.jpashop.service;
import jpabook.jpashop.domain.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;
/**
* 상품 등록
* @param item
* @return Long
*/
@Transactional
public Long saveItem(Item item){
itemRepository.save(item);
return item.getId();
}
/**
* 상품 단건 조회
* @param id
* @return Item
*/
public Item findOne(Long id){
return itemRepository.findOne(id);
}
/**
* 상품 전체 조회
* @return List<Item>
*/
public List<Item> findItems(){
return itemRepository.findAll();
}
}