liveBook · Manning

Orphan removal

As explained in Java Persistence with Spring Data and Hibernate epub

Orphan removal is a JPA association-mapping option that automatically removes a child entity when it is no longer associated with its parent.

Removing a child from an entity collection does not necessarily delete the child’s database row. On a @OneToMany association, orphanRemoval = true tells JPA to delete a child permanently when it is removed from that collection. section 8.3.3

Listing 8.24 Enabling orphan removal on a @OneToMany collection
Path: Ch08/mapping-associations/src/main/java/com/manning/javapersistence
 /ch08/onetomany/orphanremoval/Item.java
 
@Entity
public class Item {
    // . . .
 
    @OneToMany(mappedBy = "item",
               cascade = CascadeType.PERSIST, orphanRemoval = true)
    private Set<Bid> bids = new HashSet<>();
    //  . . .
}

The mapping enables orphan removal alongside CascadeType.PERSIST. The two settings address different transitions: persisting referenced children and deleting children removed from the collection. section 8.3.3

Remove one child

Fetch an Item with its bids, call item.removeBid(firstBid), and save the Item. Hibernate detects the removed Bid at transaction commit and issues a SQL DELETE for it. section 8.3.3

Choose the deletion mechanism according to the relationship:

  • Orphan removal deletes a child removed from the collection; CascadeType.REMOVE instead cascades deletion when the parent is deleted. section 8.3.3
  • Unlike clearing a collection of embeddable components, clearing entity children does not produce one bulk DELETE: Hibernate loads and removes them individually. section 8.3.3
  • Enable orphan removal only when no other database row or in-memory association needs the child. Deleting its row does not clean up other in-memory references. section 8.3.3

How Java Persistence with Spring Data and Hibernate epub covers it

How deep it goes
Shows the mapping, repository operation, commit-time detection, SQL deletion, and limits on bulk deletion and reference cleanup.
Examples
Uses an Item–Bid mapping, a repository fetch-and-remove operation, and a User association that retains an in-memory reference.
What it assumes
Assumes familiarity with entity associations and repositories while showing the mapping and removal operation.
What you can do after
Apply it via JPA @OneToMany when a removed child should be deleted and no other reference depends on it.
How it connects
Contrasts cascade persist, cascade remove, embeddable collections, foreign keys, and database-level ON DELETE CASCADE.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Java Persistence with Spring Data and Hibernate epub. The section links point to the parts of the book it draws on.