[JPA 기본] 영속성 전이 (CASCADE), 고아 객체

강신현·2022년 7월 18일
0

✅ cascade = CascadeType.ALL ✅ orphanRemoval = true

💡 영속성 전이 (CASCADE)

특정 엔티티를 영속 상태로 만들 때 연관된 엔티티도 함께 영속 상태로 만들도 싶을 때 사용
cascade = CascadeType.ALL

예: 부모 엔티티를 저장할 때 자식 엔티티도 함께 저장

  1. 영속성 전이는 연관관계를 매핑하는 것과 아무 관련이 없음
  2. 엔티티를 영속화할 때 연관된 엔티티도 함께 영속화하는 편리함을 제공할 뿐

- 사용 경우

  1. 부모와 자식의 라이프 사이클 (저장, 삭제)가 동일할 때
  2. 단일 소유자 (부모가 하나)일 때만 사용

- 사용 전

  • Parent
@Entity
public class Parent {

    @Id
    @GeneratedValue
    private Long id;

    private String name;

    @OneToMany(mappedBy = "parent")
    private List<Child> childList = new ArrayList<>();

    public void addChild(Child child){
        childList.add(child);
        child.setParent(this);
    }
    
    // getter
    // setter
}
  • Child
@Entity
public class Child {

    @Id
    @GeneratedValue
    private Long id;

    private String name;

    @ManyToOne
    @JoinColumn(name = "parent_id")
    private Parent parent;
    
    // getter
    // setter
}
  • Main
Child child1 = new Child();
Child child2 = new Child();

Parent parent = new Parent();
parent.addChild(child1);
parent.addChild(child2);

em.persist(parent);
em.persist(child1);
em.persist(child2);

em.persist 를 총 3번 해줘야 함.
Parent 를 persis할 때 child도 자동으로 persis 하게 할 수는 없을까? 👇

- 사용 후

  • Parent
    cascade = CascadeType.ALL 속성 추가
@Entity
public class Parent {

    @Id
    @GeneratedValue
    private Long id;

    private String name;

    @OneToMany(mappedBy = "parent", cascade = CascadeType.ALL)
    private List<Child> childList = new ArrayList<>();

    public void addChild(Child child){
        childList.add(child);
        child.setParent(this);
    }
    
    // getter
    // setter
}
  • Main
    Parent 를 persis할 때 child도 자동으로 persis
Child child1 = new Child();
Child child2 = new Child();

Parent parent = new Parent();
parent.addChild(child1);
parent.addChild(child2);

em.persist(parent);

- 속성

  • ALL: 모두 적용
  • PERSIST: 영속 (저장할 때만 맞춤)
  • REMOVE: 삭제
  • MERGE: 병합
  • REFRESH: REFRESH
  • DETACH: DETACH

💡 고아 객체

고아 객체 제거: 부모 엔티티와 연관관계가 끊어진 자식 엔티티를 자동으로 삭제
orphanRemoval = true

- 사용 경우

  1. 참조하는 곳이 하나일 때 (영속성 정의와 동일)
  2. 특정 엔티티가 개인 소유할 때 사용 (영속성 정의와 동일)
  3. @OneToOne, @OneToMany만 가능
  • Parent
    orphanRemoval = true 속성 추가
@Entity
public class Parent {

    @Id
    @GeneratedValue
    private Long id;

    private String name;

    @OneToMany(mappedBy = "parent", cascade = CascadeType.ALL, orphanRemoval = true)
    private List<Child> childList = new ArrayList<>();

    public void addChild(Child child){
        childList.add(child);
        child.setParent(this);
    }
    
    // getter
    // setter
}
  • Main
Child child1 = new Child();
Child child2 = new Child();

Parent parent = new Parent();
parent.addChild(child1);
parent.addChild(child2);

em.persist(parent);

em.flush();
em.clear();

Parent findParent = em.find(Parent.class, parent.getId());
findParent.getChildList().remove(0); // 부모 엔티티와 연관관계가 끊어졌으므로 0번 자식 엔티티를 자동으로 삭제한다.
profile
땅콩의 모험 (server)

0개의 댓글