Skip to content
Advertisement

Spring Boot :Deleting a blog posts shared tag only when the last post that has it is deleted

I have a dilemma trying to get a solution for this issue. I have two (can be any number) blog posts that share the same tag.

I have a set of tags for each added post so duplicate tags are not possible, so lets say I add first post with the tags “car” and “blue” and the second post with “car” and “red”. then I will have car, red, blue in the database tag table so car is only once but both posts share it which puts me in a situation of not being able to delete any of the 2 posts because of the shared tag.

How can I delete the tag only when the last post is deleted but not before(when I delete the first one)? I don’t think there is any cascade type that can help me with this issue but I may be mistaken? (I have used All and Remove but that did not work) What solution do I have?

I am using spring boot with MySQL.

If someone can point me in the right direction I would appreciate it!

L.E : For anyone having the same issue, I have used cascade = {CascadeType.MERGE, CascadeType.PERSIST} on the Post(parent) Tag(child) many to many relationship. and using a loop to delete the remaining tags after the last post has been deleted. Everything works so far.

Advertisement

Answer

You can use orphan removal option but it reinserts depending associations when there is an active relationship. You can read this blog post.

You can use event listeners and i recommend this. Write an event listener that works when a tag is deleted so with event listener you can conditionally delete the tags. You can read this for event listeners. You can use @PostRemove event.

Advertisement