0
0
SpringbootHow-ToBeginner · 4 min read

How to Use Cascade in JPA: Simple Guide with Examples

In JPA, use the cascade attribute on a relationship annotation like @OneToMany or @ManyToOne to automatically apply operations such as persist, merge, or remove to related entities. For example, @OneToMany(cascade = CascadeType.ALL) ensures all changes on the parent are cascaded to its children.
📐

Syntax

The cascade attribute is used inside relationship annotations to specify which operations should be passed from the parent entity to its related entities.

Common cascade types include:

  • PERSIST: saves the child when the parent is saved
  • MERGE: updates the child when the parent is updated
  • REMOVE: deletes the child when the parent is deleted
  • ALL: applies all cascade operations
java
@OneToMany(cascade = CascadeType.ALL)
private List<ChildEntity> children;
💻

Example

This example shows a Parent entity with a list of Child entities. Using cascade = CascadeType.ALL means saving or deleting the parent will do the same for its children automatically.

java
import jakarta.persistence.*;
import java.util.*;

@Entity
class Parent {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    private String name;

    @OneToMany(cascade = CascadeType.ALL, orphanRemoval = true)
    private List<Child> children = new ArrayList<>();

    public Parent() {}

    public Parent(String name) {
        this.name = name;
    }

    public void addChild(Child child) {
        children.add(child);
    }

    // getters and setters omitted for brevity
}

@Entity
class Child {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    private String name;

    public Child() {}

    public Child(String name) {
        this.name = name;
    }

    // getters and setters omitted for brevity
}

// Usage in a service or main method
EntityManager em = ...; // obtain entity manager
em.getTransaction().begin();
Parent parent = new Parent("Parent1");
parent.addChild(new Child("Child1"));
parent.addChild(new Child("Child2"));
em.persist(parent); // cascades persist to children
em.getTransaction().commit();
Output
Parent and its children are saved to the database in one transaction.
⚠️

Common Pitfalls

Common mistakes when using cascade in JPA include:

  • Not setting cascade when needed, so child entities are not saved or deleted automatically.
  • Using CascadeType.ALL without understanding it can delete child records unexpectedly.
  • Forgetting to use orphanRemoval = true when you want to delete children removed from collections.
  • Applying cascade on the wrong side of the relationship, which can cause errors or no effect.
java
/* Wrong: No cascade, children won't be saved automatically */
@OneToMany
private List<Child> children;

/* Right: Cascade persist and remove, children saved and deleted with parent */
@OneToMany(cascade = {CascadeType.PERSIST, CascadeType.REMOVE}, orphanRemoval = true)
private List<Child> children;
📊

Quick Reference

Cascade TypeDescription
PERSISTSave child entities when parent is saved
MERGEUpdate child entities when parent is updated
REMOVEDelete child entities when parent is deleted
REFRESHRefresh child entities when parent is refreshed
DETACHDetach child entities when parent is detached
ALLApply all cascade operations

Key Takeaways

Use the cascade attribute on JPA relationship annotations to propagate operations automatically.
CascadeType.ALL applies all operations including persist, merge, and remove to related entities.
Always consider orphanRemoval=true to delete children removed from collections.
Be careful with cascade remove to avoid accidental data loss.
Apply cascade only on the owning side of the relationship for correct behavior.