이 질문은 매우 일반적이기 때문에이 답변은 제가 블로그에 작성한 이 기사를 기반으로 합니다 .
CascadeType.REMOVE
CascadeType.REMOVE명시 적으로 구성 할 수 있는 전략 :
@OneToMany(
mappedBy = "post",
cascade = CascadeType.REMOVE
)
private List<PostComment> comments = new ArrayList<>();
또는 CascadeType.ALL전략 에서 암시 적으로 상속 :
@OneToMany(
mappedBy = "post",
cascade = CascadeType.ALL
)
private List<PostComment> comments = new ArrayList<>();
remove상위 엔티티에서 하위 엔티티로 작업 을 전파 할 수 있습니다 .
따라서 컬렉션 Post과 함께 상위 항목을 가져오고 항목을 comments제거하면 post:
Post post = entityManager.createQuery("""
select p
from Post p
join fetch p.comments
where p.id = :id
""", Post.class)
.setParameter("id", postId)
.getSingleResult();
entityManager.remove(post);
Hibernate는 세 개의 delete 문을 실행할 것입니다.
DELETE FROM post_comment
WHERE id = 2
DELETE FROM post_comment
WHERE id = 3
DELETE FROM post
WHERE id = 1
전략으로 PostComment인해 하위 엔티티가 삭제되었으며 이는 하위 엔티티도 CascadeType.REMOVE제거 된 것처럼 작동했습니다.
고아 제거 전략
orphanRemoval속성을 통해 설정해야하는 고아 제거 전략 :
@OneToMany(
mappedBy = "post",
cascade = CascadeType.ALL,
orphanRemoval = true
)
private List<PostComment> comments = new ArrayList<>();
컬렉션에서 자식 엔터티를 제거 할 때 자식 테이블 행을 제거 할 수 있습니다.
따라서 컬렉션과 Post함께 엔티티를 로드 하고 comments컬렉션에서 첫 번째 항목 PostComment을 제거하면 comments:
Post post = entityManager.createQuery("""
select p
from Post p
join fetch p.comments c
where p.id = :id
order by p.id, c.id
""", Post.class)
.setParameter("id", postId)
.getSingleResult();
post.remove(post.getComments().get(0));
Hibernate는 관련 post_comment테이블 행에 대해 DELETE 문을 실행할 것입니다 .
DELETE FROM post_comment
WHERE id = 2
이 주제에 대한 자세한 내용은 이 기사 도 확인하십시오 .