티스토리 뷰
구현 기능
- 상품 등록
- 상품 목록 조회
- 상품 수정
상품 엔티티
@Entity
@Getter @Setter
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
// 싱글 테이블 전략
@DiscriminatorColumn(name = "dtype")
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;
}
}
상품 리포지토리
@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();
}
}
상품 서비스
@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);
}
}
상품 예외
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);
}
}
'기록 > 스프링 부트 와 JPA 활용' 카테고리의 다른 글
웹 계층 개발 (0) | 2021.01.31 |
---|---|
주문 도메인 개발 (0) | 2021.01.30 |
회원 도메인 개발 (0) | 2021.01.30 |
도메인 분석 설계 (0) | 2021.01.27 |
스프링 부트와 JPA 프로젝트 환경설정 (0) | 2021.01.24 |
최근에 올라온 글
최근에 달린 댓글
- Total
- Today
- Yesterday
링크
TAG
- 스태틱 메서드
- 의존관계 주입
- 생성자 주입
- 싱글 톤
- 람다 표현식
- 기본 메서드
- JPA
- stream
- 기본 제공 함수형 인터페이스
- java8
- 싱글톤 빈
- 준영속 엔티티
- 빈 생명주기
- @configuration
- 메서드 레퍼런스
- 변경감지
- annotation container
- 싱글 톤 빈
- Functional Interface
- 프로토타입 빈
- 티스토리 Open API
- HTTP 메시지
- 클라이언트 서버 구조
- 스프링 빈 등록
- H2 DB
- Iterable
- 함수형 인터페이스
- 스프링부트
- function패키지
- completablefuture
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | |||
5 | 6 | 7 | 8 | 9 | 10 | 11 |
12 | 13 | 14 | 15 | 16 | 17 | 18 |
19 | 20 | 21 | 22 | 23 | 24 | 25 |
26 | 27 | 28 | 29 | 30 | 31 |
글 보관함