I'm facing a challenge with my Spring Boot and Hibernate application regarding comment deletion. My Comment entity is set up with a parent-child relationship, where each comment can have multiple child comments. Here's a brief overview of the Comment class structure: it has fields for an ID, ticket association, a list of child comments, a parent comment, and various other attributes.
My goal is to delete a comment along with all its child comments without Hibernate loading the entire comment tree, as the default behavior makes massive SQL select statements that are really inefficient. Unfortunately, I can't use lazy fetching in my project as a solution. I've noticed that Hibernate tries to execute large join commands during the deletion process, which leads to memory issues. Any advice on how to handle this more efficiently?
3 Answers
If your database supports it, consider implementing an `ON DELETE CASCADE` statement. This allows the database itself to handle cascading deletions when a parent comment is deleted. I’m not entirely sure how to set this up with Hibernate, but most databases should have a way to do it. Good luck with your implementation!
How do you manage comment deletions in your application? Are you allowing a comment to be marked as deleted instead of doing a hard delete? This could help in situations where you’d prefer not to remove child comments from the database immediately, letting you manage what you consider ‘deleted’ more flexibly.
One approach you could take is using a native query for deletion. Alternatively, you could annotate the parentComment field with `@OnDelete(action = OnDeleteAction.CASCADE)` to enable cascading without fetching the entire tree. However, be cautious with cascading deletes, as they can remove all child comments automatically, which might be risky if not carefully managed. It's been a while since I've used Spring/Hibernate, though, so keep that in mind!

Currently, we are performing hard deletes to ensure comments are completely removed without a trace. We want all child comments deleted immediately when a parent comment is deleted, so a soft-delete approach isn't suitable for us in this case.