JPA / Hibernate Cascade.Remove use case for @ManyT

2019-02-19 01:12发布

问题:

With the following:

//User class...

@ManyToOne(cascade=CascadeType.REMOVE)
@JoinColumn(name="INSTITUTION_ID")
public void setInstitution(final Institution institution) {
    this.institution = institution;
}

Does this mean deleting a User object would remove the Institution object associated with it? If that is the case I don't follow why this would be needed. Say for example that the institution had many users. Does this mean that deleting one of those Users deletes the institution, in which case all the other Users lose it aswell?

回答1:

You are right, it is rarely (if ever) needed and not portable construct to use CascadeType.REMOVE with ManyToMany or ManyToOne . This is documented as follows in JPA 2.0 specification:

The relationship modeling annotation constrains the use of the cascade=REMOVE specification. The cascade=REMOVE specification should only be applied to associations that are specified as OneToOne or OneToMany. Applications that apply cascade=REMOVE to other associations are not portable.

Reason why it exists is likely just that there was no reasonable way to limit allowed values of cascade to some subset of CascadeType enumeration's values.