Cascade types help manage related data automatically. They make sure changes in one object affect connected objects without extra code.
Cascade types and behavior in Spring Boot
Start learning this pattern below
Jump into concepts and practice - no test required
@OneToMany(cascade = CascadeType.ALL) private List<Child> children;
Use cascade attribute inside relationship annotations like @OneToMany, @ManyToOne, @OneToOne, or @ManyToMany.
CascadeType.ALL means all cascade operations apply: persist, merge, remove, refresh, detach.
@OneToMany(cascade = CascadeType.PERSIST) private List<Order> orders;
@OneToOne(cascade = {CascadeType.MERGE, CascadeType.REMOVE})
private Profile profile;@ManyToMany(cascade = CascadeType.DETACH) private Set<Tag> tags;
This example shows a Parent entity with children. When the parent is saved, all children are saved automatically because of CascadeType.ALL. The output shows how many children were saved and retrieved.
import jakarta.persistence.*; import java.util.*; @Entity class Parent { @Id @GeneratedValue private Long id; public Long getId() { return id; } @OneToMany(cascade = CascadeType.ALL, orphanRemoval = true) private List<Child> children = new ArrayList<>(); public Parent() {} public void addChild(Child child) { children.add(child); } public List<Child> getChildren() { return children; } } @Entity class Child { @Id @GeneratedValue private Long id; private String name; public Child() {} public Child(String name) { this.name = name; } public String getName() { return name; } } public class CascadeDemo { public static void main(String[] args) { EntityManagerFactory emf = Persistence.createEntityManagerFactory("example-unit"); EntityManager em = emf.createEntityManager(); em.getTransaction().begin(); Parent parent = new Parent(); parent.addChild(new Child("Child 1")); parent.addChild(new Child("Child 2")); em.persist(parent); // saves parent and children because of cascade em.getTransaction().commit(); em.getTransaction().begin(); Parent foundParent = em.find(Parent.class, parent.getId()); System.out.println("Children count: " + foundParent.getChildren().size()); em.getTransaction().commit(); em.close(); emf.close(); } }
Be careful with CascadeType.REMOVE to avoid accidentally deleting related data.
Use orphanRemoval = true to delete child objects if they are removed from the parent's collection.
Cascade only works on entity relationships managed by JPA, not on unrelated objects.
Cascade types automate saving, updating, deleting related entities.
Use cascade to keep related data consistent without extra code.
Choose cascade types carefully to avoid unwanted data loss.
Practice
CascadeType.ALL option do in Spring Boot JPA?Solution
Step 1: Understand CascadeType.ALL meaning
CascadeType.ALL means all cascade operations are applied to related entities automatically.Step 2: Identify included operations
These operations include persist, merge, remove, refresh, and detach, covering all common entity lifecycle events.Final Answer:
It applies all cascade operations including persist, merge, remove, refresh, and detach. -> Option AQuick Check:
CascadeType.ALL = all cascade operations [OK]
- Thinking ALL only means persist or remove
- Confusing cascade with fetch types
- Assuming cascade disables operations
Solution
Step 1: Recall correct cascade syntax
The cascade attribute expects an array or single enum value of type CascadeType.Step 2: Validate each option
@OneToMany(cascade = CascadeType.PERSIST) uses correct enum CascadeType.PERSIST. String-based options like "persist" or {"persist"} are incorrect. CascadeType.ALL.PERSIST uses invalid enum chaining.Final Answer:
@OneToMany(cascade = CascadeType.PERSIST) -> Option BQuick Check:
Use CascadeType enums, not strings [OK]
- Using string values instead of enum constants
- Trying to chain enums like ALL.PERSIST
- Omitting the cascade attribute entirely
parentRepository.delete(parent) is called?@Entity
class Parent {
@OneToMany(cascade = CascadeType.REMOVE)
List<Child> children;
}
Solution
Step 1: Understand CascadeType.REMOVE effect
CascadeType.REMOVE means deleting the parent also deletes all related children automatically.Step 2: Apply to the delete operation
Calling delete on parent triggers removal of parent and cascades delete to all children in the list.Final Answer:
Both parent and all its children are deleted from the database. -> Option CQuick Check:
REMOVE cascades delete to children [OK]
- Assuming children remain after parent delete
- Confusing REMOVE with DETACH or REFRESH
- Thinking cascade REMOVE causes errors
@Entity
class Order {
@OneToOne(cascade = CascadeType.MERGE)
Payment payment;
}
// Later in code
orderRepository.save(order);
What issue might occur?
Solution
Step 1: Understand CascadeType.MERGE behavior
CascadeType.MERGE only updates existing entities; it does not persist new ones automatically.Step 2: Analyze save operation with new payment
If payment is new (not yet saved), save(order) won't persist payment, causing an error or missing data.Final Answer:
The payment entity will not be saved if it is new, causing an error. -> Option AQuick Check:
MERGE does not persist new entities [OK]
- Assuming MERGE saves new entities
- Confusing syntax errors with runtime behavior
- Ignoring cascade effects on related entities
Customer entity with a @OneToMany relationship to Order entities. You want to ensure that when a customer is deleted, all their orders are also deleted, but when an order is updated, the customer should not be affected. Which cascade type configuration is best?Solution
Step 1: Identify cascade needed for delete
To delete all orders when customer is deleted, CascadeType.REMOVE is required.Step 2: Avoid affecting customer on order update
Using only REMOVE avoids cascading updates or persists from orders to customer, so customer stays unchanged on order update.Final Answer:
@OneToMany(cascade = CascadeType.REMOVE) -> Option DQuick Check:
REMOVE cascades delete only, no update cascade [OK]
- Using ALL cascades causing unwanted updates
- Using PERSIST or MERGE alone missing delete cascade
- Confusing DETACH with delete cascade
