javajpamany-to-manyeclipselinkcascade

JPA: implicit cascades for relationships mapped as @ManyToMany @JoinTable?


I have the following mapping:

@Entity
@Table(name = "Prequalifications")
public class Prequalification implements Serializable
{
    ...

    @ManyToMany
    @JoinTable(name = "Partnerships", joinColumns = @JoinColumn(name = "prequalification_id", referencedColumnName = "id"), inverseJoinColumns = @JoinColumn(name = "company_id", referencedColumnName = "id"))
    private Set<Company> companies;

    ...
}

In a @ManyToMany + @JoinTable mapped relationship, isn't it kind of implicit that the association (link) entities (here Partnerships) are automatically persisted, removed, etc. even though

by default, relationships have an empty cascade set

? The above quote was taken from "Pro JPA 2, by Mike Keith".

Executing

em.merge(prequalification);

on the above entity does persist the associated partnerships without any cascade types specified.

Am I correct that this implicit cascade has to be performed? This isn't mentioned anywhere I looked...


Solution

  • The rows in the join table will be inserted/deleted as part of the owning Entity (if bi-directional the side without the mappedBy). So if you persist or remove or update the Prequalification the join table rows will also be inserted or deleted.

    The target Company objects will not be cascaded to. So on remove() they will not be deleted, if the list is updated they will not be deleted unless orphanRemovla is set. Persist should also not be cascaded, but what happens when you have references to "detached" objects is somewhat of a grey area. Technically an error should be thrown, because the object is new and the relationship was not cascade persist. It may also try to insert and get a constraint error. It should not cascade the persist, although your object model is technically in an invalid state, so what occurs may depend on the provider.