JPA
JPA 영속성 전이 CASCADE
으엉어엉
2024. 8. 25. 17:59
728x90
CASCADE

Parent Class
@OneToMany(mappedBy = "parent")
private List<Child> childrenList = new ArrayList<>();
public void addChild(Child child){
childrenList.add(child);
child.setParent(this);
}
Child Class
@ManyToOne
@JoinColumn(name = "PARENT_ID")
private Parent parent;
JpaMain Class
Child child1 = new Child();
Child child2 = new Child();
Parent parent = new Parent();
parent.addChild(child1);
parent.addChild(child2);
em.persist(child1);
em.persist(child2);
em.persist(parent);
persist 를 줄이고 Parent 중심으로해서 Child를 관리할 수 있었으면 좋겠다고 생각하면 CASCADE를 사용해야한다.
Parent Class
@OneToMany(mappedBy = "parent", cascade = CascadeType.ALL)
persist를 child를 해주지 않더라도 child들이 persist 된다.

주의사항
- 영속성 전이는 연관관계를 매핑하는 것과 아무 관련이 없음
- 엔티티를 영속화할 때 연관된 엔티티도 함께 영속화하는 편리함 을 제공할 뿐
CASCADE의 종류
- ALL: 모두 적용
- PERSIST: 영속
- REMOVE: 삭제
그 이외에.. / MERGE: 병합 / REFRESH: REFRESH / DETACH: DETACH
728x90