Let's say we have many-to-one relationship where PostComment contains parent entity Post. There is no cascading here. My goal is to clean PostComments and I wonder, whether exists the way better than setting PostComment.post = null, persisting entity and then delete PostComment? I use Spring data over JPA\Hibernate, so, JPQL queries and Native queries are welcome.
CodePudding user response:
Can't you try something like this?
em.createQuery("delete from PostComment pc where pc.post = :post") .setParameter("post", postId) .executeUpdate();
CodePudding user response:
Assuming your entity Post and PostComments are managed by hibernate. Clearing the list should make hibernate realize that the comments are removed. You may need to add "orphanRemoval = true" in the @OneToMany annotation in your Post Class.
public class Post {
....
@OneToMany(orphanRemoval = true)
private List<PostComment> postComments;
....
}
Your Service with removeMethod:
@Transactional
public void clearComments() {
Optional<Post> post = postRepository.findById(1);
post.get().getPostComments.clear();
}