Created
June 4, 2025 06:40
-
-
Save jaimemin/5848ace98a14377a472f347fed6274ac to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // 가. 자식 객체 수동 삭제후 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