0 votes
in JAVA by
What is Cascading and What Are Different Types of Cascading?

1 Answer

0 votes
by
Cascading is about persistence actions involving one object propagating to other objects via an association. Cascading can apply to a variety of Hibernate actions, and it is typically transitive.

The "cascade=..." attribute of the annotation that defines the association says what actions should cascade for that association.

JPA allows you to propagate the state transition from a parent entity to a child. For this purpose, the JPA javax.persistence.CascadeType defines various cascade types:

ALL - cascades all entity state transitions

PERSIST - cascades the entity persist operation.

MERGE - cascades the entity merge operation.

REMOVE - cascades the entity remove operation.

REFRESH - cascades the entity refresh operation.

DETACH - cascades the entity detach operation.

Additionally, the CascadeType.ALL will propagate any Hibernate-specific operation, which is defined by the org.hibernate.annotations.CascadeType enum:

SAVE_UPDATE - cascades the entity saveOrUpdate operation.

REPLICATE - cascades the entity replicate operation.

LOCK - cascades the entity lock operation.

Cascading only makes sense only for Parent-Child associations (the Parent entity state transition being cascaded to its Child entities). Cascading from Child to Parent is not very useful and usually, it’s a mapping code smell.

The following examples will explain some of the aforementioned cascade operations using the following entities:

@Entity

public class Person {

    @Id

    private Long id;

    private String name;

    @OneToMany(mappedBy = "owner", cascade = CascadeType.ALL)

    private List < Phone > phones = new ArrayList < > ();

    //Getters and setters are omitted for brevity

    public void addPhone(Phone phone) {

        this.phones.add(phone);

        phone.setOwner(this);

    }

}

@Entity

public class Phone {

    @Id

    private Long id;

    @Column(name = "`number`")

    private String number;

    @ManyToOne(fetch = FetchType.LAZY)

    private Person owner;

    //Getters and setters are omitted for brevity

}
...