Search code examples
hibernatejpaspring-datahibernate-mapping

JPA ManyToMany unidirectional relationship


Lets say we have two Entities, Entity Node and Entity Cluster. A Cluster has many Nodes. A Node can belong to multiple Cluster. So in Cluster there is a @ManyToMany annotation. However Node is unaware of any Cluster it belongs to (intentional).

When I delete a Cluster I want to keep all the Nodes (in future I may add those Nodes to another Cluster) it had. So I don't need Cascade.DELETE. But If I delete a Node, all the Cluster it belonged to should be updated (the Node will be removed from them).

What is the best way to handle this using JPA ?


Solution

  • That's because Node is unaware of any Cluster it belongs to.

    If you use bidirectionnal relationship, you have to choose which side will update links between Node and Cluster. Choose the entity the most important on your business point of view... To save the association, you need to save the owning entity of the relationship.

    If you don't want bidirectionnal relationship, you need to remove the Node from all Cluster.nodes before deleting the Node itself...