Entity Relationships
Orders rarely live alone.
Introduction
Orders rarely live alone. Line items, payments, and users form relationships. Jakarta Persistence models them with @OneToOne, @OneToMany, @ManyToOne, and @ManyToMany. Ownership and fetch type decide who holds the foreign key and when SQL runs.
For Order ↔ OrderItem, the many side owns the FK (order_id on items). The one side uses mappedBy. Default collections to FetchType.LAZY. Cascade and orphanRemoval are powerful — use them when the item lifecycle is truly nested under the order.
@ManyToMany looks convenient for tags or courses, but real systems usually need join attributes (quantity, assigned_at). Prefer an explicit join entity. Eager collections are a common source of accidental full-graph loads.
Map relationships for correctness first; tune fetching per use case with join fetch or entity graphs.
Purpose of this lesson
Model Orders associations with correct ownership, LAZY defaults, and cascades that match the domain lifecycle.
Understanding the topic
The many side owns the FK; fetch lazily unless a query says otherwise.
- @ManyToOne: OrderItem → Order with
@JoinColumn. - @OneToMany(mappedBy): Order → items; inverse side.
- @OneToOne: owner holds the FK (for example Order ↔ Payment).
- @ManyToMany: prefer a join entity in production models.
- LAZY: default for collections; fetch explicitly when needed.
Step-by-step explanation
- Add
OrderItemwith@ManyToOnetoOrder. - Add
List<OrderItem> itemson Order withmappedBy, LAZY, and controlled cascade. - Helper methods
addItem/removeItemkeep both sides in sync. - Persist an order with two items; verify FK values in Postgres.
Informative example
Order and OrderItem relationship.
import jakarta.persistence.*;import java.util.ArrayList;import java.util.List;@Entitypublic class Order {@Id @GeneratedValue(strategy = GenerationType.IDENTITY)private Long id;@OneToMany(mappedBy = "order",cascade = CascadeType.ALL,orphanRemoval = true,fetch = FetchType.LAZY)private List<OrderItem> items = new ArrayList<>();public void addItem(OrderItem item) {items.add(item);item.setOrder(this);}}@Entity@Table(name = "order_items")public class OrderItem {@Id @GeneratedValue(strategy = GenerationType.IDENTITY)private Long id;@Column(nullable = false) private String sku;@Column(nullable = false) private int qty;@Column(name = "unit_cents", nullable = false) private int unitCents;@ManyToOne(fetch = FetchType.LAZY, optional = false)@JoinColumn(name = "order_id", nullable = false)private Order order;public void setOrder(Order order) { this.order = order; }}
Real-world use
Checkout creates one order header and N line items in a single transaction. Cascading from Order keeps the aggregate consistent; orphanRemoval drops lines removed before pay. Reporting queries join fetch items only when the detail screen needs them.
Security implications
Graphs can over-expose related data.
- Do not serialize full item collections without authorization review.
- Cascade remove is destructive — gate cancel/delete in the service.
- Validate that line items belong to the order being mutated.
Best practices
- Sync both sides of bidirectional associations in aggregate methods.
- Keep fetch LAZY; customize per query.
- Model join entities when the association carries data.
Common mistakes
- Putting the FK on the one side and fighting duplicate columns.
- Eager
@OneToManyloading thousands of items on every findById. - Using raw
@ManyToManythen needing extra join columns later.
Advanced interview questions
Interview Prep
Practice concise answers, then expand each card for the explanation.
1BeginnerQuestionWhich side owns the FK in OneToMany/ManyToOne?+
Answer
mappedBy to mark itself as inverse.2IntermediateQuestionWhy default collections to LAZY?+
Answer
3AdvancedQuestionWhen replace ManyToMany with a join entity?+
Answer
Hands-on exercise
Lab. Implement Order/OrderItem as above. Save an order with two items. Query items by order_id in SQL. Then load the order without fetch and confirm items are not selected until you join fetch in a repository method.
Summary
Relationships encode Orders aggregates safely when ownership and fetch are explicit. Next: query those graphs with JPQL.