JPA 프로그래밍 5. 엔티티 상태와 Cascade - KwangtaekJung/inflearn-spring-data-jpa-keesun GitHub Wiki
부모-자식의 관계를 갖는 Entity간에 cascade 설정을 하면 편리하다. ex) Post-Comment 관계에서 Post를 삭제하면 그와 관련된 Comment들도 모두 삭제된다.
-
엔티티의 상태 변화를 전파 시키는 옵션.
-
잠깐? 엔티티의 상태가 뭐지? -Transient: JPA가 모르는 상태
- Persistent: JPA가 관리중인 상태 (1차 캐시, Dirty Checking, Write Behind, ...)
- Detached: JPA가 더이상 관리하지 않는 상태.
- Removed: JPA가 관리하긴 하지만 삭제하기로 한 상태.
@Entity
@Getter @Setter
public class Comment {
@Id @GeneratedValue
private Long id;
private String title;
private String comment;
@ManyToOne
private Post post;
}
@Entity
@Getter @Setter
public class Post {
@Id @GeneratedValue
private Long id;
private String title;
@OneToMany(mappedBy = "post", cascade = CascadeType.ALL)
private Set<Comment> comments = new HashSet<>();
public void addComment(Comment comment) {
this.getComments().add(comment);
comment.setPost(this);
}
}
@Override
public void run(ApplicationArguments args) throws Exception {
Session session = entityManager.unwrap(Session.class);
Post post = session.get(Post.class, 1l);
session.delete(post);
}
Hibernate:
delete
from
comment
where
id=?
Hibernate:
delete
from
comment
where
id=?
Hibernate:
delete
from
post
where
id=?