영속성 전이(CASECADE)

박찬우·2023년 12월 27일

JPA

목록 보기
19/45

영속성 전이(CASECADE)

  • 특정 엔티티를 속 상태로 만들 때 연관된 엔티티도 함께 속 상태로 만들도 싶을 때
  • 예: 부모 엔티티를 저장할 때 자식 엔티티도 함께 저장

  • 코드(영속성전이 X)
@Entity
public class Parent {

    @Id @GeneratedValue
    private Long id;

    private String name;

    @OneToMany(mappedBy = "parent")
    private List<Child> list = new ArrayList<>();
	
@Entity
public class Child {

    @Id @GeneratedValue
    private Long id;

    private String name;

    @ManyToOne
    @JoinColumn(name = "PARENT_ID")
    private Parent parent;
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);

tx.commit();
  • 코드(영속성전이 O)
@Entity
public class Parent {

    @Id @GeneratedValue
    private Long id;

    private String name;

    @OneToMany(mappedBy = "parent", cascade = CascadeType.ALL)
    private List<Child> list = new ArrayList<>();
	
@Entity
public class Child {

    @Id @GeneratedValue
    private Long id;

    private String name;

    @ManyToOne
    @JoinColumn(name = "PARENT_ID")
    private Parent parent;
Child child1 = new Child();
Child child2 = new Child();

Parent parent = new Parent();

parent.addChild(child1);
parent.addChild(child2);

// parent의 영속성이 전이되어 child도 영속성을 가짐
em.persist(parent);

// 타입이 All, Remove이면 parent삭제 시 child 모두 삭제
// em.remove(parent);

tx.commit();

주의

  • 속성 전이는 연관관계를 매핑하는 것과 아무 관련이 없음
  • 엔티티를 영속화할 때 연관된 엔티티도 함께 영속화하는 편리함을 제공할 뿐
  • 단일 엔티티에 종송적이고 라이프 사이클이 동일하고 딱 1:1로 관계가 있을 때만 사용
    예) 게시글과 게시글의 첨부파일

종류

  • ALL : 모두 적용
  • PERSIST : 영속
  • REMOVE : 삭제
  • MERGE : 병합
  • REFRESH : REFRESH
  • DETACH : DETACH
profile
진짜 개발자가 되어보자

0개의 댓글