@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
'- 코딩 공부' 카테고리의 다른 글
API 개발 고급 - 컬렉션 조회 최적화 (1) | 2023.11.01 |
---|---|
변경 감지와 병합(Merge) (0) | 2023.09.24 |
JPA 실전 (0) | 2023.09.03 |
JPA - 객체지향 쿼리 언어1 (0) | 2023.07.31 |
JPA 정리 - 어디인지 모르겠음 (0) | 2023.06.17 |