Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Given a Hibernate/JPA entity with cascading set to ALL for a related entity:

@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?

like image 652
Steve Chambers Avatar asked Aug 31 '25 15:08

Steve Chambers


2 Answers

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.

like image 163
Dragan Bozanovic Avatar answered Sep 02 '25 16:09

Dragan Bozanovic


You can't temporarily disable cascading (to my knowledge, at least), but since you use Hibernate you can insert new entity using HQL

String hqlInsert = "insert into DelinquentAccount (id, name) select c.id, c.name from Customer c where ...";
int createdEntities = s.createQuery( hqlInsert ).executeUpdate();

There is always a "manual" solution where you remember relatedEntities in a variable for later use, and set null value as its value on Entity instance before persisting it.

like image 30
Predrag Maric Avatar answered Sep 02 '25 17:09

Predrag Maric