JAVA
JPA - 영속성 전이
HCastle
2022. 3. 14. 17:58
반응형
이 글은 JPA 공부를 하면서 참고를 위해 작성한 글입니다.
엔티티(Entity) 간에는 관계가 존재할 수 있고, 부모 엔티티가 등록 또는 삭제 될 때 자식 엔티티 또는 같이 변경되는 것을 영속성 전이라고 합니다.
예를 들어 아래와 같은 Order Entity 에 저장/삭제 를 할 때 자식엔티티인 OrderItem 또한 저장/삭제 될 수 있습니다.
@Entity
@Table(name = "orders")
@Data
public class Order {
@Id @GeneratedValue
@Column(name = "order_id")
private Long id;
@OneToMany(mappedBy = "order", cascade = CascadeType.ALL)
private List<OrderItem> orderItems = new ArrayList<>();
private LocalDateTime regTime;
}
CASCADE type 은 아래와 같습니다.
CASCADE TYPE | 설명 |
ALL | cascades all entity state transitions |
PERSIST | cascades the entity persist operation |
MERGE | cascades the entity merge operation |
DETACH | cascades the entity detach operation |
REMOVE | cascades the entity remove operation |
REFRESH | cascades the entity refresh operation |
※ 고아 객체
부모 엔티티와 연관 관계가 끊어진 자식 엔티티를 고아 객체라고 합니다.
아래와 같은 코드가 실행되게 되면 해당되는 orderItem 을 DB 에서 삭제하게 됩니다.
order.getOrderItems().remove(0); -- order 객체에서 orderItem 0번을 제거한다.
em.flush();
orphanRemoval 옵션을 false 로 설정하면 사용할 수 있으며, 기본값은 false 입니다.
다른 곳에서도 참조하는 데이터일 경우 삭제하면 문제가 될 수 있으므로 단일참조인 경우에만 사용하도록 주의하여야 합니다.
@OneToMany(mappedBy = "order", cascade = CascadeType.ALL, orphanRemoval = true)
반응형