Search code examples
jpa-2.0openjpa

Deleting and updating Many-to-Many Relationships using OpenJPA


I have a couple of entities that will be deleted. Those entities will have a couple Many-To-Many links. When updating a many-to-many link I am thinking I will just delete the original links in the joining table for that entity and just replace the link with a new link. But I am really confused on how that would work. How do you update a many-to-many relationship? Same thing goes for delete. If you have cascade for deletes set, then you would essentially delete that entity and the entities (collection, multiple entities I believe) that are linked to it. How would that work?

@Entity
@Table(name="QUICK_LAUNCH")
public class QuickLaunch implements Serializable {
...
@ManyToMany(fetch=FetchType.EAGER)
        @JoinTable(name="QUICK_LAUNCH_PROVIDER", 
        joinColumns=@JoinColumn(name="QUICK_LAUNCH_ID"),
        inverseJoinColumns=@JoinColumn(name="RESOURCE_ID"))
private List<Provider> providerList;
}

The thinking was that I would delete any links to a provider and just add new links. I could do that programatically, just delete links in the linking table, but I feel as though that should be handled by the ORM (is that an unreasonable feeling?).
Does anybody have any general words of wisdom for Deleteing Many-To-Many relationships, Maybe I could just delete and update relationships using the actual entities...

Like say I have a quickLaunch with a list of providers... I set that list of providers to null (effectively removing that list of providers from that entity I would hope) I would then set that list of providers to a new list of providers... I of course would have to set up that list programatically. Does that sounds feasable or just freaking stupid?


Solution

  • That's the way to do:

    • removing a provider from the list will remove the association between the QuickLaunch and the provider (and thus delete the corresponding row from the join table);
    • adding a provider to the list will create the association between the QuickLaunch and the provider (and thus insert a row in the join table).