spring/인프런 강의 정리
[JPA 활용 1] 5. 상품 도메인 개발
qazyj
2022. 4. 18. 16:11
구현 기능
- 상품 등록
- 상품 목록 조회
- 상품 수정
순서
- 상품 엔티티 개발 (비즈니스 로직 추가)
- 상품 리포지토리 개발
- 상품 서비스 개발, 상품 기능 테스트
상품 엔티티 개발 (비즈니스 로직 추가)
Item Entity
package jpabook.jpashop.domain.Item;
import jpabook.jpashop.domain.Category;
import jpabook.jpashop.exception.NotEnoughStockException;
import lombok.Getter;
import lombok.Setter;
import java.util.*;
import javax.persistence.*;
@Entity
@Getter
@Setter
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(name = "dtype")
public abstract class Item {
...
//==비즈니스 로직==//
/**
* stock 증가
*/
public void addStock(int quantity){
this.stockQuantity += quantity;
}
/**
* stock 감소
*/
public void removeStock(int quantity){
int restStock = this.stockQuantity - quantity;
if(restStock < 0){
throw new NotEnoughStockException("need more stock");
}
this.stockQuantity = restStock;
}
}
비즈니스 로직 추가
- 아이템 수량 추가
- 아이템 수량 제거
- 수량이 0개 이하가 되면 에러
NotEnoughStockException 예외 클래스
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);
}
}
예외처리 클래스는 처음 만들어 보았는데 RuntimeException을 상속받고 Override를 추가해주었다.
상품 리포지토리 개발
ItemRepository
package jpabook.jpashop.repository;
import jpabook.jpashop.domain.Item.Item;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Repository;
import java.util.*;
import javax.persistence.EntityManager;
@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); //merge에 대한 설명은 후에 한다고 합니다.
}
}
public Item findByOne(Long id){
return em.find(Item.class, id);
}
public List<Item> findAll(){
return em.createQuery("select i from Item i", Item.class)
.getResultList();
}
}
상품 서비스 개발
ItemService
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.*;
@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 id){
return itemRepository.findOne(id);
}
}
위와 같이 Service가 굳이 필요한 가에 대한 궁금증이 생길 수 있습니다.
이와같은 로직(Service가 위임만 한다.)에서는 Controller에서 바로 Repository에 접근해도 문제가 될 건 없다고 합니다.
테스트 코드 생성은 앞선 도메인 테스트와 다를게 없기때문에 하지 않았습니다.
출처
실전! 스프링 부트와 JPA 활용1 - 웹 애플리케이션 개발 - 인프런 | 강의
실무에 가까운 예제로, 스프링 부트와 JPA를 활용해서 웹 애플리케이션을 설계하고 개발합니다. 이 과정을 통해 스프링 부트와 JPA를 실무에서 어떻게 활용해야 하는지 이해할 수 있습니다., - 강
www.inflearn.com