Spring Boot & Microservices (50 Qs)•Part 2: Persistence, Transactions & Security (11 - 24)
What are JPA Cascade Types and Orphan Removal?
junior LevelCode ExampleState ManagementSecurity & AuthDatabases & SQL
In Simple Words:
cascade = CascadeType.ALL: Propagates entity operations (PERSIST,MERGE,REMOVE) from parent to children (e.g. savingOrderautomatically saves allOrderItemrecords).orphanRemoval = true: If a child entity is removed from the parent's collection (order.getItems().remove(item)), JPA automatically executes an SQLDELETEfor that orphaned child.
java
@OneToMany(mappedBy = "order", cascade = CascadeType.ALL, orphanRemoval = true)
private List<OrderItem> items = new ArrayList<>();