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

Tags: , , ,



i have a dilemma trying to get a solution for this issue. I am having 2(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 wich puts me in a situation of not beeing 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.

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.



Source: stackoverflow