Notice
Recent Posts
Recent Comments
Link
| 일 | 월 | 화 | 수 | 목 | 금 | 토 |
|---|---|---|---|---|---|---|
| 1 | 2 | 3 | 4 | 5 | 6 | |
| 7 | 8 | 9 | 10 | 11 | 12 | 13 |
| 14 | 15 | 16 | 17 | 18 | 19 | 20 |
| 21 | 22 | 23 | 24 | 25 | 26 | 27 |
| 28 | 29 | 30 |
Tags
- Selection Sorting
- 이스케이프 문자
- 이것이 자바다
- C programming
- Algorithm
- 메모리구조
- R
- 윤성우 열혈자료구조
- 알기쉬운 알고리즘
- C 언어 코딩 도장
- s
- JSON
- list 컬렉션
- insertion sort
- ㅅ
- stream
- datastructure
- 윤성우의 열혈 자료구조
- Stack
- Serialization
- buffer
- Graph
- coding test
- 혼자 공부하는 C언어
Archives
- Today
- Total
Engineering Note
[JPA] 영속성 전이 CASCADE 본문
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.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 프로그래밍(김영한)
'Server > JPA ORM' 카테고리의 다른 글
| [JPA] fetch join을 사용하는 이유와 한계 (0) | 2026.04.08 |
|---|---|
| [JPA] 고아객체 (0) | 2026.02.06 |
| [JPA] N+1문제가 발생하는 예(주문내역 조회) (1) | 2026.01.23 |
| [JPA] JPA에서 연관관계가 맺어진 객체를 비교(eq)하는 것은, 실제 DB에서는 그 객체의 'ID(PK) 값'을 비교하는 것과 완전히 동일하다. (0) | 2026.01.14 |
| [JPA] 영속성 전이 옵션과 연관관계 편의 메서드가 필요한 이유, 고아객체 설정 (1) | 2026.01.10 |
Comments