부모삭제 = 자식삭제
, 부모저장 = 자식저장
persist()
detach()
Child childA = new Child();
Child childB = new Child();
Parent parent = new Parent();
parent.addChild(childA); // 자식을 부모리스트에 추가 및 자식객체에 부모 설정
parent.addChild(childB); // 자식을 부모리스트에 추가 및 자식객체에 부모 설정
entityManager.persist(parent); // 영속상태 및 Insert 쿼리
entityManager.persist(childA); // 영속상태 및 Insert 쿼리
entityManager.persist(childB); // 영속상태 및 Insert 쿼리
addChild
)는 부모객체(N)에 존재한다.persist()
를 3번 호출해야된다...@Entity
@Getter
@Setter
@NoArgsConstructor
public class Parent {
@Id @GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
// ✅ Cascade Persist 설정
@OneToMany(mappedBy = "parent", cascade = CascadeType.PERSIST)
private List<Child> children = new ArrayList<>();
// 연관관계 데이터 설정 메서드
void addChild(Child child){
this.children.add(child); // 자식객체를 부모 자식리스트에 추가
child.setParent(this); // 자식객체의 부모객체(this)를 설정
}
}
Child childA = new Child();
Child childB = new Child();
Parent parent = new Parent();
parent.addChild(childA); // 부모의 자식리스트에 추가 및 자식객체에 부모 설정
parent.addChild(childB); // 부모의 자식리스트에 추가 및 자식객체에 부모 설정
entityManager.persist(parent); // ✅ 부모만 영속상태 및 Insert 쿼리
Parent
객체 안에 있는 children
변수에 CascadeType.PERSIST
설정을 하였다.Parent
객체가 영속상태가 되면 해당 객체(Child)도 영속상태가 된다.라는 뜻이다!CascadeType.REMOVE
처럼 동작한다!@OneToMany(mappedBy = "parent", orphanRemoval = true)
private List<Child> children = new ArrayList<>();
@OneToMany(mappedBy = "parent", cascade = CascadeType.ALL, orphanRemoval = true)
private List<Child> children = new ArrayList<>();
DDD의 Aggregate Root
개념을 구현할 때 용이하다.김영한 자바 ORM 표준 JPA 프로그래밍
들어도 들어도 헷갈리는 remove와 고아객체의 차이.. ㅠㅠ