Module 3: Entity Relationships (The Connected Shelves)
📚 Module 3: Entity Relationships
Focus: Moving from “Single Tables” to “Connected Systems.”
In the real world, data is rarely alone. A Category has many Products. A Customer has many Orders. In JPA, we use Annotations to connect our shelves together.
🏗️ Step 1: One-to-Many (The “Parent-Child” Link)
This is the most common relationship. One “Parent” owns many “Children.”
🧩 The Analogy: The Folder and the Files
- One Folder (The Parent) can contain 100 Files (The Children).
- If you delete the Folder, you probably want to delete the Files too (Cascading).
In Code:
@Entity
public class Category {
@Id
private Long id;
private String name;
@OneToMany(mappedBy = "category")
private List<Product> products; // One category has many products
}🏗️ Step 2: Many-to-One (The “Reference”)
This is the opposite side of the relationship. Every child points back to its parent.
🧩 The Analogy: The Store Tag
- Every Product (The Child) has a tag that says: “I belong to the Electronics Category.”
- Many products can have the same tag.
In Code:
@Entity
public class Product {
@Id
private Long id;
@ManyToOne
@JoinColumn(name = "category_id") // The SQL foreign key
private Category category;
}🏗️ Step 3: Cascading & Fetching (The “Delivery”)
- CascadeType.ALL: If I save the Parent, automatically save all the Children.
- FetchType.LAZY: Don’t load the Children from the database until I specifically ask for them. (This saves memory!).
🥅 Module 3 Review
- @OneToMany: One parent, many children.
- @ManyToOne: Many children pointing to one parent.
- mappedBy: Tells Spring who is the “Boss” of the relationship.
- JoinColumn: The actual column in SQL that holds the connection (Foreign Key).