영속성전이(CASCADE)와 고아객체

학습 페이지

영속성 전이(CASCADE)


영속성 전이 : 저장

parent와 child의 양방향 연관관계를 다음과 같이 맺는다고 해보자.

@Getter
@Setter
@Entity
public class Parent {
    @Id
    @GeneratedValue
    private Long id;

    private String name;

    @OneToMany(mappedBy = "parent")
    private List<child> childlist = new ArrayList<>();

    public void addChild(child child){ //연관관계 편의 메서드
        childlist.add(child);
        child.setParent(this);
    }
}
@Getter
@Setter
@Entity
public class child {
    @Id
    @GeneratedValue
    private Long Id;

    @ManyToOne
    @JoinColumn(name = "parent_id") //child가 주
    private Parent parent;
}
            child child1 = new child(); //child1생성
            child child2 = new child(); //child2생성
            Parent parent = new Parent(); //parent생성
            
            parent.addChild(child1);
            parent.addChild(child2);

생성된 child1과 child2, parent를 영속화하려면 persist()를 세번 해야 한다. 즉 각각 persist해줘야 한다.

            em3.persist(parent);
            em3.persist(child1);
            em3.persist(child2);

결론부터 말하면.. 영속성 전이는 이 과정이 귀찮아서 사용하는 기능이다.

parent중심으로 코드를 작성하고 있는데, child를 일일이 persist()하는 것이 생산성이 떨어지는 일이라고 생각할 수 있다.

이럴때는 다음의 설정을 한다.