
김영한 강사님 [실전! 스프링 부트와 JPA 활용1 - 웹 애플리케이션 개발] 강의 참조
비즈니스 로직(Business logic) : 컴퓨터 프로그램에서 실세계의 규칙에 따라 데이터를 생성·표시·저장·변경하는 부분
엔티티(데이터를 가지고 있는 곳)에서 비즈니스 로직을 작성하는 것이 응집도를 높여줌
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;
}
}
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);}
}