hoondev

[Spring JPA] 영속석 전이와 고아객체 본문

Spring JPA

[Spring JPA] 영속석 전이와 고아객체

hoondev3 2023. 2. 3. 15:52

영속성 전이

영속성 전이는 특정 엔티티를 영속 상태로 만들 때 연관된 엔티티도 함께 영속 상태로 만드는 것이다.

@Entity
public class Parent {

    @Id @GeneratedValue
    private Long id;

    private String name;

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

    public void addchild(Child child) {
        childes.add(child);
        child.setParent(this);
    }
}
@Entity
public class Child {

    @Id @GeneratedValue
    private Long id;

    private String name;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "parent_id")
    private Parent parent;

    public void setParent(Parent parent) {
    	this.parent = parent;
    }
}
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);

이렇게 다음과 같이 parent에 연관관계를 설정한 child 일일이 모두 영속화 하는 작업을 거쳐야 하는 것을 볼 수 있다.

 

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

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

em.persist(parent);

parent에 @OneToMany의 cascade 옵션을 설정해주면 parnet와 연관된 객체들을 자동으로 영속화 해준다.

 

주의

영속성 전이는 연관관계를 매핑하는 것과 아무 관련이 없다.

엔티티를 영속화할 때 연관된 엔티티도 함께 영속화하는 편리함 을 제공할 뿐이다.

 

CascadeType 종류

  • ALL: 모두 적용
  • PERSIST: 영속
  • REMOVE: 삭제
  • MERGE: 병합
  • REFRESH: REFRESH 
  • DETACH: DETACH

주로 사용하게 되는건 ALL과 PERSIST이다.

 

고아 객체

고아 객체란 부모 엔티티와 연관관계가 끊어진 자식 엔티티를 말한다.

orphanRemoval = true 라는 옵션이 있는데 이 옵션을 키면 고아 객체 제거 기능이 있다.

개념적으로 부모를 제거하면 자식은 고아가 된다. 따라서 고아 객체 제거 기능을 활성화 하면, 부모를 제거할 때 자식도 함께 제거된다. 이것은 CascadeType.REMOVE처럼 동작한다.

 

Parent parent1 = em.find(Parent.class, id); parent1.getChildren().remove(0);

DELETE FROM CHILD WHERE ID=?

 

주의

참조하는 곳이 하나일때 즉 단일소유자일 사용해야한다.

@OneToOne, @OneToMany만 가능

 

영속성 전이 + 고아 객체, 생명주기

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

이렇게 부모가 저장되면 영속화되면 자식도 영속화되고 부모가 삭제되면 자식도 같이 삭제된다.

 

Reference

https://www.inflearn.com/course/ORM-JPA-Basic

'Spring JPA' 카테고리의 다른 글

[Spring JPA] 임베디드 타입(복합 값 타입)  (1) 2023.02.06
[Spring JPA] 값 타입  (0) 2023.02.05
[Spring JPA] 즉시 로딩과 지연 로딩  (1) 2023.02.02
[Spring JPA] 프록시  (0) 2023.02.01
[Spring JPA] @MappedSuperclass  (0) 2023.01.31
Comments