Spring Boot Tutorial 0/110 lessons ~6 min read Lesson 30

    Entity Relationships

    Relationships model how entities reference each other.

    Course progress0%
    Focus
    4 guided sections
    Practice signal
    Examples included
    Career prep
    Foundation builder

    Introduction

    Relationships model how entities reference each other. Get the ownership and fetch strategy right, or you'll fight Hibernate forever.

    Understanding the topic

    The four mappings, owners marked with ★:

    • @OneToOne — User ★ ↔ Profile. Owner has the FK.
    • @OneToMany / @ManyToOne — Order ↔ ★ Item. The many side owns the FK. Always.
    • @ManyToMany — Student ↔ Course via a join table. Avoid in real apps; model the join as a first-class entity.

    Informative example

    ts
    @Entity
    public class Order {
    @Id @GeneratedValue Long id;
    @OneToMany(
    mappedBy = "order", // 'order' field on OrderItem owns the FK
    cascade = CascadeType.ALL,
    orphanRemoval = true,
    fetch = FetchType.LAZY
    )
    private List<OrderItem> items = new ArrayList<>();
    }
    @Entity
    public class OrderItem {
    @Id @GeneratedValue Long id;
    @ManyToOne(fetch = FetchType.LAZY, optional = false)
    @JoinColumn(name = "order_id")
    private Order order;
    }

    Best practices

    • Own the FK on the many side; mappedBy on the one.
    • Default fetch to LAZY on every relation.
    • Replace @ManyToMany with a join entity — you'll need extra columns soon enough.
    Ready to mark this lesson complete?Track your journey across the entire course.