참고 : 인프런 [ 실전! 스프링 부트와 JPA 활용1 - 웹 애플리케이션 개발 - 김영한 ]
이번에는 상품 엔티티 자체에 비즈니스 로직을 추가해보자. (도메인 주도 설계)
-> 객체 지향적
~/domain/Item.java
...
//==비즈니스 로직//
/**
* stock 증가
*/
public void addStock(int qauntity){
this.stockQuantity+=qauntity;
}
/**
* stock 감소
*/
public void removeStock(int qauntity){
int restStock= this.stockQuantity-qauntity;
if(restStock<0){
throw new NotEnoughStockException("need more stock");
}
this.stockQuantity=restStock;
}
Item 엔티티가 StockQauntity 정보를 가지고 있기 때문에, 엔티티 자체에서 비즈니스 로직을 다루는 것이 좋다.
상품의 재고가 0개 이하일때 발생하는 익셉션을 생성해보자.
~/exception/NotEnoughStockException.java
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);
}
public NotEnoughStockException(String need_more_stock) {
}
}
NotEnoughStockException은 RuntimeException을 extends 하고, 오버라이드 해준다.
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){
...
}
public List<Item> findAll(){
...
}
}
@Service
@Transactional(readOnly = true) //기본값
@RequiredArgsConstructor
public class ItemService {
private final ItemRepository itemRepository;
@Transactional //readOnly=false
public void saveItem(Item item){
...
}
public List<Item> findItems(){
...
}
public Item findOne(Long itemId){
...
}
}