Steve Chambers Steve Chambers - 1 year ago 70
Java Question

Is it possible to temporarily disable cascading for a Hibernate entity?

Given a Hibernate/JPA entity with cascading set to

for a related entity:

public class Entity {
@OneToMany(cascade = CascadeType.ALL, orphanRemoval = true, mappedBy = "entity")
private Set<RelatedEntities> relatedEntities;

Is it possible to temporarily turn off the cascading, e.g. to allow Entity to be persisted without also persisting its relatedEntities?

Answer Source

No, it is not possible to do it, and at least according to my modest opinion, it would not be a good thing to do so either. When other developers look at the mappings and the code that does persist/merge/delete... they would expect the cascades to be applied and introduce the unexpected behavior if they oversee that the cascades are temporarily disabled somewhere else for the code they are about to change.

However, you can map to the same table a new entity class which does not have the fields that are cascaded. Then just use that entity in situations in which you don't want the cascades to be applied.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download