Engineering Note

[JPA] 영속성 전이 CASCADE 본문

Server/JPA ORM

[JPA] 영속성 전이 CASCADE

Software Engineer Kim 2026. 2. 6. 19:09

8.4 영속성 전이 CASCADE

부모의 엔티티를 저장할 때 자식 엔티티도 저장할 것인지 설정하게 해주는 기능

 

 

8.4.1 영속성 전이: 저장

 

 

//예제 8.14 부모 엔티티

@Entity
public class Parent {

 @Id @GeneratedValue
 private Long id;
 
 @OneToMany(mappedBy = "parent")
 private List<Child> children = new ArrayList<Child>();

}


//예제 8.15 자식 엔티티
@Entity
public class Child {
 @Id @GeneratedValue
 private Long id;
 
 @ManyToOne
 private Parent parent;
}

 

 

영속성 전이 설정을 하지 않고 Entity를 저장하는 예제

private static void saveNoCasecade(EntityManager em){
 //부모 저장
 Parent parent = new Parent();
 
 //1번 자식 저장
 Child child1 = new Child();
 child1.setParent(parent); //자식 -> 부모 연관관계 설정
 parent.getChildren(child1); //부모 -> 자식


//2번 자식 저장
Child child2 = new Child();
child2.setParent(parent); //자식 -> 부모 연관관계 설정
parent.getChildren(child2); //부모 -> 자식
em.persist(child2);
}

 

JPA에서 엔티티를 저장할 때 연관된 모든 엔티티는 영속 상태여야 한다. 따라서 예제를 보면 부모 엔티티와 자식 엔티티 모두 개별적으로 영속 상태로 만든다.

=> 영속성 전이를 사용하면 부모만 영속 상태로 만들면 연관된 자식까지 한 번에 영속 상태로 만들 수 있다.

 

 

영속성 전이 설정을 통한 저장 

@Entity
public class Parent {

 @Id @GeneratedValue
 private Long id;
 
 @OneToMany(mappedBy = "parent", cascade = CascadeType.PERSIST)
 private List<Child> children = new ArrayList<Child>();

}

private static void saveWithCascade(EntityManager em) {

 Child child1 = new Child();
 Child child2 = new Child();
 
 Parent parent = new Parent();
 child1.setParent(parent);
 child2.setParent(parent);
 parent.getChildren().add(child1);
 parent.getChildren().add(child2);


//부모 저장, 연관된 자식들 함께 저장
em.persist(parent);
}

 

CasecadeType.PERSIST 옵션 덕분에 부모만 영속화하면, 자식 엔티티까지 함께 영속화해서 저장한다.

 

내부 동작 과정

8.11 CASCADE 실행

 

 

8.4.2 영속성 전이 : 삭제

영속성 전이는 엔티티를 삭제할 때도 사용할 수 있다. 

 

 @OneToMany(mappedBy = "parent", cascade = CascadeType.REMOVE)
 private List<Child> children = new ArrayList<Child>();
Parent findParent = em.find(Parent.class, 1L);
em.remove(findParent);

 

 

만약 CasecadeType.REMOVE를 설정하지 않고,  em.remove(findParent);코드를 실행하면 부모 엔티티만 삭제된다. 하지만 데이터베이스의 부모 로우를 삭제하는 순간 자식 테이블에 걸려 있는 외래 키 제약조건으로 인해, 데이터베이스에서 외래키 무결성 예외가 발생한다.

 

 

 

 

참고자료 : JPA 프로그래밍(김영한)

 

Comments