What is orphanRemoval?

Key Points

Example: CategoryBlogPost

Contextual Example: RestaurantFoodItem

Since the previous queries referenced the Food Delivery App, let’s apply orphanRemoval to RestaurantFoodItem:

@Entity
public class Restaurant extends BaseEntity {
    private String name;
    private String address;
    private String city;
    private String description;

    @OneToMany(mappedBy = "chosenRestaurant", cascade = CascadeType.ALL, orphanRemoval = true)
    private List<FoodItem> foodItems = new ArrayList<>();

    // Helper methods
    public void addFoodItem(FoodItem item) {
        foodItems.add(item);
        item.setChosenRestaurant(this);
    }

    public void removeFoodItem(FoodItem item) {
        foodItems.remove(item);
        item.setChosenRestaurant(null);
    }

    // Getters and Setters
}

@Entity
public class FoodItem extends BaseEntity {
    private String itemName;
    private String itemDescription;
    private boolean isVeg;
    private int price;

    @ManyToOne
    @JoinColumn(name = "restaurant_id", nullable = false)
    private Restaurant chosenRestaurant;

    // Getters and Setters
}

Distinction: CascadeType.REMOVE vs. orphanRemoval

Notes