- 코딩 공부
JPA - 주문 도메인 개발
방개입니다
2023. 9. 10. 21:51
@Autowired
EntityManager em;
em.flush();
flush를 하면 디비에 쿼리가 나가는 것이다.
Transactional
롤백한다
@setter를 쓰는 것 보다 아래와 같이 핵심 메서드를 만들어서 세터를 구성하는 것이 좋다.
@ManyToMany(mappedBy = "items")
private List<Category> categories = new ArrayList<>();
//아래와 같이 핵심 메서드를 만들어서 세터를 구성해야한다
/*
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;
}
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);
}
}
아래에서 persist는 쿼리 날리는 것이고 merge는 강제로 업데이트 하는 것이다.
public void save(Item item){
if(item.getId() == null){
em.persist(item);
}else {
em.merge(item);
}
}
생성자 주입 어노테이션이다
@RequiredArgsConstructor