BE전문가 프로젝트

영속성 전이 :CASCADE 본문

JPA

영속성 전이 :CASCADE

원호보고서 2022. 10. 31. 22:52
  • 특정 엔티티를 영속 상태로 만들 때 연관된 엔티티도 함께 연속성상태로 만들고 싶을 때
  • 부모 엔티티르 저장할 때 자식 엔티티도 함께 저장
  • 연관관계, 지연로딩 전혀 관계가 없음
@Entity
public class Parent {

    @Id @GeneratedValue
    private Long id;

    private String name;

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

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

    @Id @GeneratedValue
    private Long id;

    private String name;

    @ManyToOne
    @JoinColumn(name = "parent_id")
    private Parent parent;
}
public class JPAMain {
    public static void main(String[] args) {
        EntityManagerFactory emf = Persistence.createEntityManagerFactory("hello");
        EntityManager em = emf.createEntityManager();

        EntityTransaction tx = em.getTransaction();
        tx.begin();                                     //트랜잭션 시작

        try {
            Child child1 = new Child();
            Child child2 = new Child();
            
            Parent parent = new Parent();
            
            parent.addChild(child1);
            parent.addChild(child2);
            
            em.persist(parent);
            
            tx.commit();
        }catch (Exception e){
            tx.rollback();
        }finally {
            em.close();
        }
        emf.close();
    }
}

 

밑에 자식 요소들도 한번에 persist할 수 있다.

 

영속성 전이: CASCADE - 주의

  • 영속성 전이는 연관관계를 매핑하는 것과 아무 관련이 없음
  • 엔티티를 영속화할 때 연관된 엔티티도 함께 영속화하는 편리함을 제공할 뿐
  • 하나의 부모가 자식들을 관리할 때(게시판 or 파일) 사용하기에 유리함, 다른 경우에는 사용 지양
  • 단일 엔티티에 완전히 종속적일때 사용 권장, parent와 child의 라이프 사이클이 거의 비슷할 때
종류 설명
ALL 모두 적용
PERSIST 영속
REMOVE 삭제
MERGE 병합
REFRESH REFRESH
DETACH DETACH

 

 

고아 객체

  • 고아 객체 제거: 부모 엔티티와 연관관계가 끊어진 자식 엔티티를 자동으로 삭제
  • orphanRemoval = true
  • Parent parent1 = em.find(Parent.class, id);                                                                                                                      parent1.getChildren().remove(0); //자식 엔티티를 컬렉션에서 제거
  • DELETE FROM CHILD WHERE ID = ?
public class JPAMain {
    public static void main(String[] args) {
        EntityManagerFactory emf = Persistence.createEntityManagerFactory("hello");
        EntityManager em = emf.createEntityManager();

        EntityTransaction tx = em.getTransaction();
        tx.begin();                                     //트랜잭션 시작

        try {
            Child child1 = new Child();
            Child child2 = new Child();
            Parent parent = new Parent();

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

            em.flush();
            em.clear();

            Parent foundParent = em.find(Parent.class, parent.getId());
            foundParent.getChildren().remove(0);

            tx.commit();
        }catch (Exception e){
            tx.rollback();
        }finally {
            em.close();
        }
        emf.close();
    }
}

컬랙션에서 제외된 객체는 삭제가 된다.

 

고아 객체 - 주의

  • 참조가 제거된 엔티티는 다른  곳에서 참조하지 않는 고아 객체로 보고 삭제하는 기능
  • 참조하는 곳이 하나일 때 사용해야함!
  • 특정 엔티티가 개인 소유할 때 사용
  • @OneToMany, @OneToOne만 가능
  • 참고: 개념적으로 부모를 제거하면 자식은 고아가 된다. 따라서 고아 객체 제거 기능을 활성화 하면, 부모를 제거할 때 자식도 함께 제거된다. 이것은 CascadeType.REMOVE처럼 동작한다.

 

영속성 전이 + 고아 객체, 생명주기 전부 사용할 경우

  • CascaedType.ALL + orphanRemovel=true
  • 스스로 생명주기를 관리하는 엔티티는 em.persist()로 영속화, em.remove()로 제거
  • 두 옵션을 모두 활성화 하면 부모 엔티티를 통해서 자식의 생명 주기도 관리할 수 있음
  • 도메인 주도 설계(DDD)의 Aggregate Root개념을 구현할 때 유용

'JPA' 카테고리의 다른 글

기본값 타입  (0) 2022.11.01
쇼핑몰 만들기 4 - 연관관계 관리  (0) 2022.10.31
영속성 전이 :CASCADE  (0) 2022.10.31
즉시 로딩과 지연 로딩  (0) 2022.10.31
Proxy(프록시)  (0) 2022.10.30
Comments