JPA Part 3 — Relationships
@OneToOne, @OneToMany, @ManyToOne, @ManyToMany, cascade types, fetch strategies
- Map all four JPA relationship types with correct owning side
- Choose between EAGER and LAZY fetching strategies
- Configure cascade types to manage child entities automatically
Series:
Concept and Coding — JPA Series Part: 3 — Entity Relationships Prerequisites: JPA Part 1 (JDBC basics), JPA Part 2 (Architecture), JPA 1-to-1 Mappings
Table of Contents
- Relationship Mapping — Concepts Recap
- One-to-Many — Unidirectional
- Orphan Removal
- One-to-Many — Bidirectional
- Owing Side vs Inverse Side — Deep Explanation
- Many-to-One — Unidirectional
- Many-to-One — Bidirectional
- Many-to-Many — Unidirectional
- Many-to-Many — Bidirectional
- Comparison Table — All Mappings
- Common Mistakes & Best Practices
- Interview Notes
- Practice Questions
- Summary
1. Relationship Mapping Concepts Recap
Before diving into each mapping type, it is important to firmly establish the vocabulary used throughout this guide. Confusing these terms is the single most common source of mistakes in JPA mapping.
1.1 Unidirectional vs Bidirectional
| Term | Meaning |
|---|---|
| Unidirectional | Only one entity has a reference (field) to the other. Navigation is possible in one direction only. |
| Bidirectional | Both entities have a reference to each other. Navigation is possible from either side. |
1.2 Parent vs Child
- Parent: The entity whose existence is not dependent on the other. If the parent is deleted, the child typically cannot exist independently.
- Child: The entity whose existence depends on the parent.
Example: A User can have many Orders. If the User is deleted, those Orders have no owner — so User is the parent, Order is the child.
1.3 Owing Side vs Inverse Side
This is the most commonly confused concept in JPA bidirectional mappings.
| Term | Definition | Identifier in Code |
|---|---|---|
| Owing Side | The entity whose table holds the foreign key column | Has @JoinColumn annotation |
| Inverse Side | The entity whose table does NOT hold the foreign key | Has mappedBy attribute |
Rule: Whichever entity's table contains the foreign key column is the owing side, regardless of whether it is the parent or the child.
1.4 Lazy vs Eager Loading (Quick Recap)
| Strategy | Behaviour | Default For |
|---|---|---|
| LAZY | Related entities are loaded only when accessed in code | @OneToMany, @ManyToMany |
| EAGER | Related entities are loaded immediately with the parent query | @ManyToOne, @OneToOne |
1.5 Cascade Types (Quick Recap)
| Type | Effect |
|---|---|
PERSIST | Save child when parent is saved |
MERGE | Update child when parent is updated |
REMOVE | Delete child when parent is deleted |
REFRESH | Refresh child when parent is refreshed |
DETACH | Detach child when parent is detached |
ALL | All of the above |
2. One-to-Many Unidirectional
2.1 Overview
One-to-Many means one record in the parent entity is associated with multiple records in the child entity.
Real-world example: One User can have many Orders.
1User (1) ─────────────────── Order (many)2 │ │3 │ User 1 ◄────────────── Order 14 │ ◄────────────── Order 25 │ ◄────────────── Order 36 │7 │ User 2 ◄────────────── Order 4Unidirectional means only the User entity has a reference to Order. The Order entity has no reference back to User in the Java class.
2.2 Default Behavior Junction Table
By default, when you annotate a field with @OneToMany, JPA creates a new join table to store the relationship. This is because the parent entity (User) has only one row — it cannot hold a variable number of foreign keys in a single row.
Default table structure (without @JoinColumn):
1user_details table user_detail_order_detail table order_detail table2────────────────── ────────────────────────────── ─────────────────3id | name | phone user_id | order_id id | product_name4───┼──────┼────── ────────┼───────── ───┼────────────51 │ Alice│ 9876 1 │ 1 1 │ Ice Cream62 │ Bob │ 5432 1 │ 2 2 │ Cold Drink7 1 │ 3 3 │ BurgerThis junction table is created automatically by JPA. You do not need to create or map it yourself.
2.3 Better Approach `@JoinColumn` in Child Table
The recommended approach for one-to-many is to store the foreign key directly in the child table (order table), avoiding the extra junction table entirely.
To do this, add @JoinColumn to the @OneToMany annotation. This tells JPA: "Do not create a new table. Instead, add a foreign key column in the child table."
Resulting table structure:
1user_details table order_detail table2────────────────── ──────────────────────────────────────3id | name | phone id | product_name | user_id_fk4───┼──────┼────── ───┼─────────────┼───────────51 │ Alice│ 9876 1 │ Ice Cream │ 162 │ Bob │ 5432 2 │ Cold Drink │ 17 3 │ Burger │ 22.4 Entity Classes
◆ `UserDetails.java` (Parent One side)
1import jakarta.persistence.*;2import java.util.List;3
4@Entity5@Table(name = "user_details")6public class UserDetails {7
8 @Id9 @GeneratedValue(strategy = GenerationType.IDENTITY)10 private Long id;11
12 private String name;13 private String phone;14
15 // One User → Many Orders16 @OneToMany(17 cascade = CascadeType.ALL, // All operations propagate to child18 fetch = FetchType.LAZY // Orders loaded only when accessed (default)19 )20 @JoinColumn(21 name = "user_id_fk", // Column name in the ORDER table (child)22 referencedColumnName = "id" // This references the "id" column in USER table23 )24 private List<OrderDetails> orders;25
26 // No-arg constructor (mandatory for JPA)27 public UserDetails() {}28
29 // Getters and Setters30 public Long getId() { return id; }31 public void setId(Long id) { this.id = id; }32
33 public String getName() { return name; }34 public void setName(String name) { this.name = name; }35
36 public String getPhone() { return phone; }37 public void setPhone(String phone) { this.phone = phone; }38
39 public List<OrderDetails> getOrders() { return orders; }40 public void setOrders(List<OrderDetails> orders) { this.orders = orders; }41}◆ `OrderDetails.java` (Child Many side)
1import jakarta.persistence.*;2
3@Entity4@Table(name = "order_details")5public class OrderDetails {6
7 @Id8 @GeneratedValue(strategy = GenerationType.IDENTITY)9 private Long id;10
11 private String productName;12
13 // No-arg constructor (mandatory for JPA)14 public OrderDetails() {}15
16 // Getters and Setters17 public Long getId() { return id; }18 public void setId(Long id) { this.id = id; }19
20 public String getProductName() { return productName; }21 public void setProductName(String productName) { this.productName = productName; }22}OrderDetails) has no field referencing UserDetails. Navigation is only possible from UserDetails → OrderDetails.2.5 Repository
1@Repository2public interface UserDetailRepository extends JpaRepository<UserDetails, Long> {}3
4@Repository5public interface OrderDetailRepository extends JpaRepository<OrderDetails, Long> {}2.6 Service Layer Save and Fetch
1@Service2public class UserService {3
4 @Autowired5 private UserDetailRepository userRepo;6
7 @Transactional8 public UserDetails saveUser() {9 // Create two orders (child entities)10 OrderDetails order1 = new OrderDetails();11 order1.setProductName("Ice Cream");12
13 OrderDetails order2 = new OrderDetails();14 order2.setProductName("Cold Drink");15
16 // Create the user (parent entity)17 UserDetails user = new UserDetails();18 user.setName("Alice");19 user.setPhone("9876543210");20 user.setOrders(List.of(order1, order2));21
22 // CascadeType.ALL ensures orders are also inserted23 return userRepo.save(user);24 // SQL: INSERT INTO user_details ...25 // INSERT INTO order_details ... (x2)26 // UPDATE order_details SET user_id_fk = ? ... (x2)27 }28
29 public UserDetails getUser(Long id) {30 return userRepo.findById(id).orElse(null);31 // SQL: SELECT * FROM user_details WHERE id = ?32 // Orders are NOT fetched yet (LAZY)33 // They are fetched only when getOrders() is called34 }35}2.7 Demonstrating Lazy Loading
1@Service2public class UserService {3
4 @Autowired5 private UserDetailRepository userRepo;6
7 @Transactional // Required to keep session open for lazy loading8 public UserDTO getUserWithOrders(Long id) {9 // Step 1: Only user_details table is queried10 UserDetails user = userRepo.findById(id).orElseThrow();11 // SQL: SELECT * FROM user_details WHERE id = ?12
13 System.out.println(">> User fetched. Orders NOT yet loaded.");14
15 // Step 2: Now map to DTO — when getOrders() is called, THEN the query fires16 UserDTO dto = new UserDTO();17 dto.setId(user.getId());18 dto.setName(user.getName());19
20 System.out.println(">> About to access orders...");21
22 // Step 3: This triggers the lazy load23 List<OrderDetails> orders = user.getOrders();24 // SQL: SELECT * FROM order_details WHERE user_id_fk = ?25
26 System.out.println(">> Orders now loaded: " + orders.size());27
28 dto.setOrders(orders);29 return dto;30 }31}Console Output:
1Hibernate: SELECT * FROM user_details WHERE id = ?2>> User fetched. Orders NOT yet loaded.3>> About to access orders...4Hibernate: SELECT * FROM order_details WHERE user_id_fk = ?5>> Orders now loaded: 2getOrders() is called, making the lazy loading visible. If you return the entity directly from a REST controller, Jackson's serializer will call all getters automatically (including getOrders()), triggering the lazy load invisibly and causing confusion.2.8 Eager Loading Alternative
1@OneToMany(2 cascade = CascadeType.ALL,3 fetch = FetchType.EAGER // Load orders immediately with the user4)5@JoinColumn(name = "user_id_fk", referencedColumnName = "id")6private List<OrderDetails> orders;SQL generated with EAGER:
1SELECT u.*, o.*2FROM user_details u3LEFT OUTER JOIN order_details o ON u.id = o.user_id_fk4WHERE u.id = ?With LAZY, the two queries are separate. With EAGER, they are joined in one query.
2.9 Architecture Diagram `@JoinColumn` vs Default
@JoinColumn over the default junction table approach. The junction table approach is best suited for many-to-many relationships.3. Orphan Removal
3.1 What Is an Orphan?
An orphan is a child entity that has been removed from its parent's collection in Java code, but whose corresponding row in the database still exists (or has its foreign key set to null) with no valid parent reference.
Scenario:
1Initial state:2 User 1 → [Order 1, Order 2, Order 3, Order 4]3
4After Java update:5 User 1 → [Order 1, Order 2, Order 3] (Order 4 removed from collection)6
7Without orphan removal:8 order_details DB: Order 4 still exists with user_id_fk = NULL ← ORPHANOrder 4 is now an orphan — it has no parent, but it still occupies a row in the database.
3.2 Orphan Removal vs Cascade Delete Key Difference
This is a very common interview question.
| Feature | Trigger | What happens |
|---|---|---|
Cascade Delete (CascadeType.REMOVE) | You delete the parent | All children are also deleted from DB |
Orphan Removal (orphanRemoval = true) | You remove a child from the parent's collection (not deleting the parent) | That child row is deleted from DB |
3.3 Default Behavior (Without Orphan Removal)
1@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY)2@JoinColumn(name = "user_id_fk", referencedColumnName = "id")3private List<OrderDetails> orders;4// orphanRemoval = false ← This is the defaultWhat happens when you remove an order from the collection and call save:
1@Transactional2public void removeFirstOrder(Long userId) {3 UserDetails user = userRepo.findById(userId).orElseThrow();4 user.getOrders().remove(0); // Remove first order from Java collection5 userRepo.save(user); // Save = UPDATE (not DELETE)6}SQL generated:
1UPDATE order_details SET user_id_fk = NULL WHERE id = ?2-- Order row still exists! Just its FK is set to null. It is now an orphan.Database after:
1order_details:2id | product_name | user_id_fk3───┼──────────────┼───────────41 │ Ice Cream │ NULL ← Orphan! Still in DB, no parent52 │ Cold Drink │ 13.4 With Orphan Removal Enabled
1@OneToMany(2 cascade = CascadeType.ALL,3 fetch = FetchType.LAZY,4 orphanRemoval = true // ← Enable orphan cleanup5)6@JoinColumn(name = "user_id_fk", referencedColumnName = "id")7private List<OrderDetails> orders;Same Java code, different result:
1@Transactional2public void removeFirstOrder(Long userId) {3 UserDetails user = userRepo.findById(userId).orElseThrow();4 user.getOrders().remove(0);5 userRepo.save(user);6}SQL generated:
1-- Step 1: Update FK to null (JPA internal step)2UPDATE order_details SET user_id_fk = NULL WHERE id = ?3
4-- Step 2: Delete the orphaned row5DELETE FROM order_details WHERE id = ?Database after:
1order_details:2id | product_name | user_id_fk3───┼──────────────┼───────────42 │ Cold Drink │ 15-- Ice Cream row is GONE. Properly cleaned up.orphanRemoval = true works through the Persistence Context. When you remove an entity from the parent's collection, the Persistence Context detects that this entity no longer has a parent reference and marks it for deletion on the next flush.3.5 Complete Example with Orphan Removal
1@RestController2@RequestMapping("/api/users")3public class UserController {4
5 @Autowired6 private UserService userService;7
8 // Step 1: Create user with 2 orders9 @PostMapping10 public UserDetails createUser() {11 return userService.createUserWithOrders();12 }13
14 // Step 2: Remove first order (orphan removal demo)15 @GetMapping("/remove-first-order/{id}")16 public UserDetails removeFirstOrder(@PathVariable Long id) {17 return userService.removeFirstOrder(id);18 }19}20
21@Service22public class UserService {23
24 @Autowired25 private UserDetailRepository userRepo;26
27 @Transactional28 public UserDetails createUserWithOrders() {29 OrderDetails o1 = new OrderDetails();30 o1.setProductName("Ice Cream");31
32 OrderDetails o2 = new OrderDetails();33 o2.setProductName("Cold Drink");34
35 UserDetails user = new UserDetails();36 user.setName("Alice");37 user.setPhone("9876543210");38 user.setOrders(new ArrayList<>(List.of(o1, o2)));39
40 return userRepo.save(user);41 }42
43 @Transactional44 public UserDetails removeFirstOrder(Long userId) {45 UserDetails user = userRepo.findById(userId).orElseThrow();46 user.getOrders().remove(0); // Remove from collection only47 return userRepo.save(user); // orphanRemoval = true → DELETE issued48 }49}4. One-to-Many Bidirectional
4.1 Overview
In bidirectional one-to-many:
- The parent (
User) has aList→ the@OneToMany(inverse) side - The child (
Order) has aUserDetailsfield → the@ManyToOne(owing) side
The child table still holds the foreign key — this is why the child is the owing side in one-to-many bidirectional.
4.2 Owing Side Determination
In one-to-many bidirectional:
1User table: id | name | phone ← NO foreign key → INVERSE side2Order table: id | productName | user_id_fk ← HAS foreign key → OWING sideThe order table holds the foreign key → OrderDetails is the owing side.
4.3 Entity Classes
◆ `OrderDetails.java` Owing Side
1@Entity2@Table(name = "order_details")3public class OrderDetails {4
5 @Id6 @GeneratedValue(strategy = GenerationType.IDENTITY)7 private Long id;8
9 private String productName;10
11 // Owing side: this table holds the foreign key12 @ManyToOne(cascade = CascadeType.ALL)13 @JoinColumn(14 name = "user_id_owing_fk", // Column name in THIS (order) table15 referencedColumnName = "id" // References the "id" column of user_details16 )17 private UserDetails userDetails;18
19 public OrderDetails() {}20
21 // Getters and Setters22 public Long getId() { return id; }23 public void setId(Long id) { this.id = id; }24
25 public String getProductName() { return productName; }26 public void setProductName(String productName) { this.productName = productName; }27
28 public UserDetails getUserDetails() { return userDetails; }29 public void setUserDetails(UserDetails userDetails) { this.userDetails = userDetails; }30}◆ `UserDetails.java` Inverse Side
1@Entity2@Table(name = "user_details")3@JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property = "id")4public class UserDetails {5
6 @Id7 @GeneratedValue(strategy = GenerationType.IDENTITY)8 private Long id;9
10 private String name;11 private String phone;12
13 // Inverse side: this table does NOT hold the foreign key14 // mappedBy = the field name in OrderDetails that owns the relationship15 @OneToMany(mappedBy = "userDetails", cascade = CascadeType.ALL, fetch = FetchType.LAZY)16 private List<OrderDetails> orders;17
18 public UserDetails() {}19
20 // Getters and Setters21 public Long getId() { return id; }22 public void setId(Long id) { this.id = id; }23
24 public String getName() { return name; }25 public void setName(String name) { this.name = name; }26
27 public String getPhone() { return phone; }28 public void setPhone(String phone) { this.phone = phone; }29
30 public List<OrderDetails> getOrders() { return orders; }31 public void setOrders(List<OrderDetails> orders) { this.orders = orders; }32}4.4 The Critical Step Setting Both Sides of the Relationship
Since OrderDetails is the owing side, JPA uses its userDetails field to determine what foreign key value to write to the database. The mappedBy collection in UserDetails is just a Java-side reference — JPA does not use it to populate the foreign key.
If you only set the inverse side (the list), the FK will be NULL:
1// ❌ WRONG — Setting only the inverse side2UserDetails user = new UserDetails();3user.setName("Alice");4
5OrderDetails o1 = new OrderDetails();6o1.setProductName("Ice Cream");7
8user.setOrders(List.of(o1)); // Setting the inverse side only9userRepo.save(user);10// Result: order saved, but user_id_owing_fk = NULL in order_details table!You MUST also set the owing side:
1// ✅ CORRECT — Setting both sides2@Transactional3public UserDetails saveUser() {4 UserDetails user = new UserDetails();5 user.setName("Alice");6 user.setPhone("9876543210");7
8 OrderDetails o1 = new OrderDetails();9 o1.setProductName("Ice Cream");10 o1.setUserDetails(user); // ← Owing side: MUST be set explicitly11
12 OrderDetails o2 = new OrderDetails();13 o2.setProductName("Cold Drink");14 o2.setUserDetails(user); // ← Owing side: MUST be set explicitly15
16 user.setOrders(new ArrayList<>(List.of(o1, o2))); // ← Inverse side (Java reference)17
18 return userRepo.save(user);19}Helper method pattern (recommended):
1// Inside UserDetails.java — use a helper to keep both sides in sync2public void addOrder(OrderDetails order) {3 if (orders == null) orders = new ArrayList<>();4 orders.add(order); // Add to inverse side collection5 order.setUserDetails(this); // Set owing side reference6}7
8// Usage:9user.addOrder(o1);10user.addOrder(o2);11userRepo.save(user);4.5 Preventing JSON Serialization Recursion
In bidirectional mappings, if you serialize User to JSON, Jackson calls getOrders(). For each order, it calls getUserDetails(). Then for that user, it calls getOrders() again — infinite recursion.
Two solutions:
Option 1: @JsonIdentityInfo (used in the example above — recommended for complex graphs)
1@Entity2@JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property = "id")3public class UserDetails { ... }This makes Jackson serialize each object by its id on second encounter, breaking the cycle.
Option 2: @JsonIgnore (simpler — recommended for most cases)
1// In OrderDetails.java — ignore the back-reference to parent2@ManyToOne(cascade = CascadeType.ALL)3@JoinColumn(name = "user_id_owing_fk", referencedColumnName = "id")4@JsonIgnore // ← Do not serialize the parent reference5private UserDetails userDetails;@JsonIgnore on the child side is the simplest approach. When you fetch a user, you get all their orders. When you serialize an order, you don't get the user back — which is usually the desired behavior anyway (you already have the user's context).5. Owing Side vs Inverse Side Deep Explanation
Summary Table by Mapping Type
| Mapping | Who holds FK in DB? | Owing Side | Inverse Side |
|---|---|---|---|
@OneToOne (from Part 2) | Parent table | Parent | Child |
@OneToMany | Child table | Child | Parent |
@ManyToOne | Child table | Child | Parent |
@ManyToMany | Neither (new join table) | Your choice | Your choice |
Visual Summary
Annotation Placement Rule
1Owing Side → @JoinColumn (or @JoinTable for ManyToMany)2Inverse Side → mappedBy = "fieldNameOnOwingSide"6. Many-to-One Unidirectional
6.1 Overview
Many-to-One is the same relationship as One-to-Many, just viewed from the child's perspective:
- One-to-Many: "One User has many Orders" (looking from parent)
- Many-to-One: "Many Orders belong to one User" (looking from child)
The database schema is identical. Only the annotation and which class holds the reference differs.
In many-to-one unidirectional, the child (Order) knows about the parent (User), but the parent (User) does NOT know about the children. There is no List in UserDetails.
6.2 Entity Classes
◆ `UserDetails.java` Parent (No knowledge of children)
1@Entity2@Table(name = "user_details")3public class UserDetails {4
5 @Id6 @GeneratedValue(strategy = GenerationType.IDENTITY)7 private Long id;8
9 private String name;10 private String phone;11
12 // NO List<OrderDetails> here — parent does not know about children13 // This is what makes it ManyToOne unidirectional14
15 public UserDetails() {}16
17 // Getters and Setters18 public Long getId() { return id; }19 public void setId(Long id) { this.id = id; }20
21 public String getName() { return name; }22 public void setName(String name) { this.name = name; }23
24 public String getPhone() { return phone; }25 public void setPhone(String phone) { this.phone = phone; }26}◆ `OrderDetails.java` Child (Knows about parent)
1@Entity2@Table(name = "order_details")3public class OrderDetails {4
5 @Id6 @GeneratedValue(strategy = GenerationType.IDENTITY)7 private Long id;8
9 private String productName;10
11 // Many orders → One user12 @ManyToOne(cascade = CascadeType.ALL)13 @JoinColumn(14 name = "user_id_fk", // FK column in order_details table15 referencedColumnName = "id" // References id in user_details16 )17 private UserDetails userDetails;18
19 public OrderDetails() {}20
21 // Getters and Setters22 public Long getId() { return id; }23 public void setId(Long id) { this.id = id; }24
25 public String getProductName() { return productName; }26 public void setProductName(String productName) { this.productName = productName; }27
28 public UserDetails getUserDetails() { return userDetails; }29 public void setUserDetails(UserDetails userDetails) { this.userDetails = userDetails; }30}6.3 Comparison: One-to-Many vs Many-to-One Unidirectional
| Aspect | One-to-Many Unidirectional | Many-to-One Unidirectional |
|---|---|---|
| "Talking from" | Parent → Child | Child → Parent |
| Reference in | Parent has List | Child has Parent reference |
| Annotation on parent | @OneToMany | Nothing |
| Annotation on child | Nothing | @ManyToOne |
| DB schema | Identical | Identical |
| FK location | Child table | Child table |
| Navigation | Parent → Children only | Child → Parent only |
6.4 Save Example
1@Transactional2public OrderDetails createOrder() {3 // Create parent (must exist first, or cascade handles it)4 UserDetails user = new UserDetails();5 user.setName("Alice");6 user.setPhone("9876543210");7
8 // Create child and link to parent9 OrderDetails order = new OrderDetails();10 order.setProductName("Ice Cream");11 order.setUserDetails(user); // Child knows its parent12
13 // Save child — CascadeType.ALL persists the user too14 return orderRepo.save(order);15 // SQL: INSERT INTO user_details ...16 // INSERT INTO order_details ... (with user_id_fk set)17}7. Many-to-One Bidirectional
7.1 Overview
Many-to-One bidirectional is exactly the same as One-to-Many bidirectional. The code, annotations, and database schema are identical.
The only conceptual difference is the starting perspective:
- One-to-Many Bidirectional: you start thinking from the parent side (user has many orders, and orders know their user)
- Many-to-One Bidirectional: you start thinking from the child side (many orders belong to one user, and users can see their orders)
Same entities, same annotations, same foreign key — just a different mental framing.
1// OneToMany bidirectional uses:2// Parent: @OneToMany(mappedBy = "userDetails")3// Child: @ManyToOne + @JoinColumn4
5// ManyToOne bidirectional uses:6// Parent: @OneToMany(mappedBy = "userDetails") ← SAME7// Child: @ManyToOne + @JoinColumn ← SAME8. Many-to-Many Unidirectional
8.1 Overview
Many-to-Many means records in entity A can be associated with multiple records in entity B, AND records in entity B can also be associated with multiple records in entity A.
Real-world example: An Order can contain many Products. A Product can appear in many Orders.
1Order 1 ──────── Product 12 ──────── Product 23Order 2 ──────── Product 14 ──────── Product 3Key characteristics:
- No parent-child relationship — neither entity depends on the other for existence
- Always requires a junction (join) table — there is no single column that can hold the association
- Either entity can be the owing side — it is a design choice
8.2 Database Structure
A many-to-many relationship always creates a new junction table:
1order_details table order_product (junction) product_details table2────────────────── ──────────────────────── ─────────────────────────3id | order_number order_id | product_id id | name | price4───┼──────────── ─────────┼─────────── ───┼────────────┼──────51 │ ORD-001 1 │ 1 1 │ Ice Cream │ 50.062 │ ORD-002 1 │ 2 2 │ Cold Ring │ 30.07 2 │ 2 3 │ Burger │ 80.0This junction table is created and managed automatically by JPA when you use @ManyToMany with @JoinTable.
8.3 Entity Classes
◆ `ProductDetails.java`
1@Entity2@Table(name = "product_details")3public class ProductDetails {4
5 @Id6 @GeneratedValue(strategy = GenerationType.IDENTITY)7 private Long id;8
9 private String name;10 private double price;11
12 // No reference to OrderDetails — unidirectional (order → product only)13
14 public ProductDetails() {}15
16 // Getters and Setters17 public Long getId() { return id; }18 public void setId(Long id) { this.id = id; }19
20 public String getName() { return name; }21 public void setName(String name) { this.name = name; }22
23 public double getPrice() { return price; }24 public void setPrice(double price) { this.price = price; }25}◆ `OrderDetails.java` Owing Side
1@Entity2@Table(name = "order_details")3public class OrderDetails {4
5 @Id6 @GeneratedValue(strategy = GenerationType.IDENTITY)7 private Long orderNumber;8
9 // Owing side: this entity is responsible for creating and managing the junction table10 @ManyToMany(cascade = {CascadeType.PERSIST, CascadeType.MERGE})11 @JoinTable(12 name = "order_product", // Name of the junction table13 joinColumns = @JoinColumn(name = "order_id"), // FK for THIS entity (order)14 inverseJoinColumns = @JoinColumn(name = "product_id") // FK for the OTHER entity (product)15 )16 private List<ProductDetails> productDetails;17
18 public OrderDetails() {}19
20 // Getters and Setters21 public Long getOrderNumber() { return orderNumber; }22 public void setOrderNumber(Long orderNumber) { this.orderNumber = orderNumber; }23
24 public List<ProductDetails> getProductDetails() { return productDetails; }25 public void setProductDetails(List<ProductDetails> productDetails) {26 this.productDetails = productDetails;27 }28}@JoinTable:
- joinColumns = the foreign key column for the entity on which this annotation is placed (the owing side — OrderDetails)
- inverseJoinColumns = the foreign key column for the other entity (ProductDetails)8.4 Repositories
1@Repository2public interface OrderDetailRepository extends JpaRepository<OrderDetails, Long> {}3
4@Repository5public interface ProductDetailRepository extends JpaRepository<ProductDetails, Long> {}8.5 Full Flow Create Products, Then Create Order Linked to Products
1@RestController2@RequestMapping("/api")3public class ProductController {4
5 @Autowired6 private ProductDetailRepository productRepo;7
8 @PostMapping("/product")9 public ProductDetails createProduct(@RequestBody ProductDetails product) {10 return productRepo.save(product);11 }12}13
14@RestController15@RequestMapping("/api")16public class OrderController {17
18 @Autowired19 private OrderDetailRepository orderRepo;20
21 @Autowired22 private ProductDetailRepository productRepo;23
24 @PostMapping("/order")25 @Transactional26 public OrderDetails createOrder(@RequestBody OrderRequest request) {27 // Step 1: Fetch the existing products by their IDs28 List<ProductDetails> products = request.getProductIds().stream()29 .map(id -> productRepo.findById(id).orElseThrow())30 .collect(Collectors.toList());31
32 // Step 2: Create the order and associate it with those products33 OrderDetails order = new OrderDetails();34 order.setProductDetails(products);35
36 // Step 3: JPA automatically populates the order_product junction table37 return orderRepo.save(order);38 // SQL: INSERT INTO order_details ...39 // INSERT INTO order_product (order_id, product_id) ... (for each product)40 }41}Step-by-Step Demo:
11. POST /api/product → { "name": "Ice Cream", "price": 50.0 } → Product ID: 122. POST /api/product → { "name": "Cold Ring", "price": 30.0 } → Product ID: 23
43. POST /api/order → { "productIds": [1, 2] }5
6SQL:7 INSERT INTO order_details (order_number) VALUES (DEFAULT) → order_number: 18 INSERT INTO order_product (order_id, product_id) VALUES (1, 1)9 INSERT INTO order_product (order_id, product_id) VALUES (1, 2)10
114. POST /api/order → { "productIds": [2] }12
13SQL:14 INSERT INTO order_details (order_number) VALUES (DEFAULT) → order_number: 215 INSERT INTO order_product (order_id, product_id) VALUES (2, 2)Final DB state:
1order_details: 1, 22product_details: 1 (Ice Cream), 2 (Cold Ring)3order_product: (1,1), (1,2), (2,2)OrderDetails is the owing side (has @JoinTable, not mappedBy), JPA automatically manages the order_id and product_id in the junction table. You do not need to write any code to insert into order_product — JPA handles it.9. Many-to-Many Bidirectional
9.1 Overview
In many-to-many bidirectional, both entities hold a reference to each other. You can navigate from Order → Products AND from Product → Orders.
The database schema is identical to unidirectional — the same junction table exists. The only difference is that ProductDetails now also has a List field.
9.2 Deciding Owing vs Inverse in Many-to-Many
Since neither entity holds the foreign key (the junction table does), either entity can be the owing side. Your choice should be based on business logic:
Which entity drives the association in your application?
In an e-commerce system, orders are created and products are associated to them (not the other way around). So OrderDetails should be the owing side — it creates and manages the junction table.
If you choose the wrong entity as the owing side, operations from the inverse side will NOT automatically update the junction table, and you must handle it manually.
9.3 Entity Classes Bidirectional
◆ `OrderDetails.java` Owing Side (unchanged from unidirectional)
1@Entity2@Table(name = "order_details")3public class OrderDetails {4
5 @Id6 @GeneratedValue(strategy = GenerationType.IDENTITY)7 private Long orderNumber;8
9 // Owing side — has @JoinTable10 @ManyToMany(cascade = {CascadeType.PERSIST, CascadeType.MERGE})11 @JoinTable(12 name = "order_product",13 joinColumns = @JoinColumn(name = "order_id"),14 inverseJoinColumns = @JoinColumn(name = "product_id")15 )16 private List<ProductDetails> productDetails;17
18 public OrderDetails() {}19
20 public Long getOrderNumber() { return orderNumber; }21 public void setOrderNumber(Long orderNumber) { this.orderNumber = orderNumber; }22
23 public List<ProductDetails> getProductDetails() { return productDetails; }24 public void setProductDetails(List<ProductDetails> productDetails) {25 this.productDetails = productDetails;26 }27}◆ `ProductDetails.java` Inverse Side (new: now has reference back to orders)
1@Entity2@Table(name = "product_details")3@JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property = "id")4public class ProductDetails {5
6 @Id7 @GeneratedValue(strategy = GenerationType.IDENTITY)8 private Long id;9
10 private String name;11 private double price;12
13 // Inverse side — has mappedBy pointing to the field in OrderDetails14 @ManyToMany(mappedBy = "productDetails")15 private List<OrderDetails> orders;16
17 public ProductDetails() {}18
19 // Getters and Setters20 public Long getId() { return id; }21 public void setId(Long id) { this.id = id; }22
23 public String getName() { return name; }24 public void setName(String name) { this.name = name; }25
26 public double getPrice() { return price; }27 public void setPrice(double price) { this.price = price; }28
29 public List<OrderDetails> getOrders() { return orders; }30 public void setOrders(List<OrderDetails> orders) { this.orders = orders; }31}9.4 Critical Warning Inverse Side Does NOT Manage the Junction Table
1// ✅ CORRECT: Creating association from the OWING side (OrderDetails)2// JPA automatically inserts into order_product junction table3OrderDetails order = new OrderDetails();4order.setProductDetails(List.of(product1, product2));5orderRepo.save(order);6// Junction table CORRECTLY populated7
8// ❌ WRONG: Creating association from the INVERSE side (ProductDetails) only9ProductDetails product = new ProductDetails();10product.setName("Burger");11product.setOrders(List.of(order1, order2)); // mappedBy — JPA ignores this for DB12productRepo.save(product);13// Junction table NOT updated — order_product remains unchanged!mappedBy, that side is a Java-only reference. JPA does not use it to write to the database. Only the owing side (@JoinTable) controls what gets written to the junction table. If you need to create associations from the inverse side, you must also update the owing side's collection.Correct bidirectional helper:
1// In OrderDetails.java2public void addProduct(ProductDetails product) {3 if (productDetails == null) productDetails = new ArrayList<>();4 productDetails.add(product); // Update owing side5 product.getOrders().add(this); // Update inverse side (Java only)6}9.5 Complete Bidirectional Architecture Diagram
10. Comparison Table All Mappings
| Mapping | Direction | FK Location | Default Fetch | New Table? | Annotation on Parent | Annotation on Child |
|---|---|---|---|---|---|---|
@OneToMany Unidirectional | Parent → Child | Child table (with @JoinColumn) or junction table (default) | LAZY | Only if no @JoinColumn | @OneToMany @JoinColumn | None |
@OneToMany Bidirectional | Both | Child table | LAZY | No | @OneToMany(mappedBy=) | @ManyToOne @JoinColumn |
@ManyToOne Unidirectional | Child → Parent | Child table | EAGER | No | None | @ManyToOne @JoinColumn |
@ManyToOne Bidirectional | Both | Child table | EAGER/LAZY | No | @OneToMany(mappedBy=) | @ManyToOne @JoinColumn |
@ManyToMany Unidirectional | One direction | Junction table | LAZY | Yes (always) | @ManyToMany @JoinTable | None |
@ManyToMany Bidirectional | Both | Junction table | LAZY | Yes (always) | @ManyToMany @JoinTable | @ManyToMany(mappedBy=) |
11. Common Mistakes & Best Practices
Common Mistakes
◆ Not Setting the Owing Side in Bidirectional Mapping
1// WRONG: Only setting the inverse side2user.setOrders(List.of(order1, order2));3// orderDetails.userDetails is never set → user_id_fk = NULL in DB4
5// CORRECT: Set both sides6order1.setUserDetails(user);7order2.setUserDetails(user);8user.setOrders(List.of(order1, order2));◆ Expecting Orphan Removal Without Enabling It
1// WRONG: Removing from collection and expecting DB row to disappear2user.getOrders().remove(0);3userRepo.save(user);4// Without orphanRemoval = true, the row stays with FK = NULL5
6// CORRECT:7@OneToMany(cascade = CascadeType.ALL, orphanRemoval = true)◆ Using CascadeType.ALL on ManyToMany (Danger!)
1// DANGEROUS: CascadeType.ALL on ManyToMany2@ManyToMany(cascade = CascadeType.ALL)3// If you delete an order, ALL associated products are also deleted!4// Products may be associated with other orders — now those orders have no products.5
6// CORRECT: Only cascade PERSIST and MERGE for ManyToMany7@ManyToMany(cascade = {CascadeType.PERSIST, CascadeType.MERGE})CascadeType.ALL or CascadeType.REMOVE on @ManyToMany relationships. Since both entities are independent, deleting one should not cascade-delete the other. It would cause data corruption — other associations pointing to the deleted entity would break.◆ Infinite Recursion Without `@JsonIgnore` or `@JsonIdentityInfo`
1// WRONG: Bidirectional entities returned directly in REST response2@GetMapping("/users/{id}")3public UserDetails getUser(@PathVariable Long id) {4 return userRepo.findById(id).orElseThrow();5 // UserDetails has List<OrderDetails>6 // OrderDetails has UserDetails → infinite JSON recursion → StackOverflowError7}8
9// CORRECT: Use DTO, @JsonIgnore, or @JsonIdentityInfoBest Practices
- Prefer
@JoinColumnover junction table for one-to-many — it is simpler and faster. - Use junction tables only for many-to-many — that is what they are designed for.
- Always use DTOs in REST responses for bidirectional entities to avoid serialization issues.
- Use helper methods (e.g.,
addOrder(),addProduct()) to keep both sides of bidirectional relationships in sync. - Avoid
CascadeType.ALLon@ManyToMany— only cascadePERSISTandMERGE. - Enable
orphanRemoval = truewhenever child entities should not exist without a parent. - Choose the owing side based on business flow — whichever entity "creates" or "drives" the association should be the owing side.
- Use
@JsonIgnoreon the inverse side of bidirectional relationships in REST APIs, unless you specifically need navigation from both sides in JSON responses.
12. Interview Notes
Most Commonly Asked Questions
Q: What is the difference between @OneToMany and @ManyToOne?
They represent the same relationship from opposite perspectives.@OneToManyis placed on the parent entity (one user, many orders).@ManyToOneis placed on the child entity (many orders, one user). The database schema is identical in both cases — the child table always holds the foreign key.
Q: What is the owing side and inverse side in JPA?
The owing side is the entity whose table contains the foreign key column. It is annotated with@JoinColumn(or@JoinTablefor many-to-many). The inverse side does not hold the FK and usesmappedBy. Only the owing side controls what is written to the database for the relationship.
Q: What is orphan removal? How is it different from cascade delete?
Cascade delete
(CascadeType.REMOVE): When you delete the parent, all children are deleted too. Orphan removal (orphanRemoval = true): When you remove a child from the parent's collection (without deleting the parent), that child row is automatically deleted from the database. Orphan removal handles detached children; cascade delete handles parent deletion propagation.
Q: When is a junction table created by JPA?
By default,@OneToManywithout@JoinColumncreates a junction table.@ManyToManyalways creates a junction table. Adding@JoinColumnto a@OneToManyprevents the junction table and puts the FK directly in the child table instead.
Q: Why should you not use CascadeType.ALL with @ManyToMany?
In a many-to-many relationship, both entities are independent — neither depends on the other for existence. UsingCascadeType.REMOVE(included inALL) means deleting one entity would cascade-delete its associated entities, which may be associated with other entities too, causing data corruption. OnlyPERSISTandMERGEare safe to cascade in many-to-many.
Q: How do you prevent infinite recursion in bidirectional JPA entities when serializing to JSON?
Two approaches: (1) Use@JsonIgnoreon the inverse side's back-reference field, so Jackson doesn't follow it. (2) Use@JsonIdentityInfoon both entities so Jackson uses the object's ID on repeated encounters instead of recursing. Using DTOs is the cleanest architectural solution.
Q: In a @ManyToMany bidirectional mapping, why does setting the inverse side's collection not update the junction table?
Because the inverse side usesmappedBy, which tells JPA: "this side does not own the relationship — do not generate any FK management SQL from here." Only the owing side (with@JoinTable) controls the junction table. Setting only the inverse side's collection is a Java-only operation and has no effect on the database.
Q: What is the default fetch type for @OneToMany and @ManyToMany?
Both default toFetchType.LAZY. Related entities are not loaded from the database until you access the collection in your code.@ManyToOneand@OneToOnedefault toFetchType.EAGER.
Q: In one-to-many bidirectional, the parent is the inverse side — explain why.
Because the child table holds the foreign key column, not the parent table. The owing side is defined by who holds the FK. Since the child holds the FK, the child entity is the owing side. The parent, whose table has no FK column, is therefore the inverse side.
13. Practice Questions
Easy
- What annotation do you use for a one-to-many relationship in JPA?
- Where is the foreign key stored in a one-to-many relationship?
- What does
orphanRemoval = truedo? - What is the default fetch type for
@OneToMany? - Which annotation marks the inverse side of a bidirectional relationship?
Medium
- Explain the difference between
cascadeType.REMOVEandorphanRemoval. - In a bidirectional
@OneToMany/@ManyToOnemapping — which entity is the owing side and why? - Why must you set both sides of a bidirectional relationship when saving in JPA?
- Write entity classes for a
Course↔Studentmany-to-many bidirectional relationship. A course can have many students and a student can enroll in many courses. - What SQL is generated when you use
@JoinColumnon@OneToManyvs when you omit it? - Why is
CascadeType.ALLdangerous on@ManyToMany?
Hard
- You have a
Projectentity and aDeveloperentity with a many-to-many relationship. A developer works on multiple projects and a project has multiple developers. Design the full JPA mapping (bidirectional), including which side should be owing and why. Write all entity classes, repositories, and a service method that assigns two existing developers to a new project. - Implement the orphan removal scenario from scratch: create a
Teamwith 3Playerentities, then remove the middle player from the team's collection and save. Trace the exact SQL statements JPA will generate. - You have a bidirectional
@ManyToMany. A junior developer sets only the inverse side's collection and callssave(). The junction table is not updated. Explain why, and show the correct fix. - Compare the SQL queries generated for fetching a
Userwith theirOrdersusing: (a) LAZY loading with DTO mapping, (b) EAGER loading. When would you choose each?
14. Summary
1MAPPING CHEAT SHEET2───────────────────────────────────────────────────────────────────────3
4ONE-TO-MANY:5 • One parent → many children6 • FK lives in CHILD table (use @JoinColumn to enforce this)7 • Default creates a junction table (avoid this for 1:N)8 • Default fetch: LAZY9 • Parent is INVERSE side (mappedBy)10 • Child is OWING side (@JoinColumn)11
12MANY-TO-ONE:13 • Many children → one parent14 • Same as OneToMany, opposite perspective15 • Child has @ManyToOne + @JoinColumn (child is owing)16 • Parent has no annotation (unidirectional) or @OneToMany(mappedBy=) (bidirectional)17 • DB schema: identical to OneToMany18
19MANY-TO-MANY:20 • Many ↔ Many21 • Always creates a junction table22 • No parent-child concept — both are independent23 • Owing side: @JoinTable (your design choice)24 • Inverse side: @ManyToMany(mappedBy=)25 • Never use CascadeType.ALL / REMOVE on @ManyToMany26 • Default fetch: LAZY27
28ORPHAN REMOVAL:29 • Different from cascade delete30 • Cascade delete: parent deleted → children deleted31 • Orphan removal: child removed from collection → child's DB row deleted32 • Enable with: orphanRemoval = true on @OneToMany33
34OWING vs INVERSE:35 • Owing = table holds FK = has @JoinColumn or @JoinTable36 • Inverse = table has no FK = has mappedBy37 • Only owing side controls DB writes for the relationship38 • Bidirectional: must set BOTH sides in Java code39
40SERIALIZATION:41 • Bidirectional = risk of infinite JSON recursion42 • Fix: @JsonIgnore on inverse side (simplest)43 • Fix: @JsonIdentityInfo on both entities (for complex graphs)44 • Best: use DTOs to control what is returnedNext Up:
JPA — Custom Queries (JPQL, Native Queries, @Query annotation) and Criteria API.
Mastery check
How well can you recall this?
Finished this lesson?