Skip to content

Instantly share code, notes, and snippets.

@abdullahEmumba
Forked from jaimemin/.java
Created June 4, 2025 06:42
Show Gist options
  • Save abdullahEmumba/31a88e7da77e42fad69b30f053a7af72 to your computer and use it in GitHub Desktop.
Save abdullahEmumba/31a88e7da77e42fad69b30f053a7af72 to your computer and use it in GitHub Desktop.
// 가. 자식 객체 수동 삭제후 flush한 뒤 부모 삭제
List<Post> posts = entityManager.createQuery("select p from Post p join fetch p.comments", Post.class).getResultList();
// 자식 엔티티 먼저 삭제
for (Post post : posts) {
post.getComments().clear(); // orphanRemoval=true이면 자동 삭제됨
}
entityManager.flush(); // 자식 DELETE 실행
// 부모 엔티티 삭제
for (Post post : posts) {
entityManager.remove(post);
}
entityManager.flush(); // 부모 DELETE 실행
// 나. JPQL Bulk DELETE로 자식 엔티티 먼저 삭제
List<Post> posts = entityManager.createQuery("select p from Post p", Post.class).getResultList();
entityManager.createQuery("DELETE FROM PostComment c WHERE c.post IN :posts")
.setParameter("posts", posts)
.executeUpdate();
for (Post post : posts) {
entityManager.remove(post);
}
entityManager.flush();
// 다. DB FK에 ON DELETE CASCADE 설정
ALTER TABLE post_comment
ADD CONSTRAINT fk_post_comment_post
FOREIGN KEY (post_id) REFERENCES post(id) ON DELETE CASCADE;
List<Post> posts = entityManager.createQuery("select p from Post p", Post.class).getResultList();
for (Post post : posts) {
entityManager.remove(post); // Post만 삭제해도 DB가 자식(PostComment) 자동 삭제
}
entityManager.flush();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment