JPA Associations
Bidirectional associations, mappedBy, join table configuration, orphan removal
- Configure bidirectional relationships with mappedBy
- Control join table name and columns with @JoinTable
- Enable orphan removal for dependent entities
A comprehensive study guide covering JPA/Hibernate entity relationships, cascade types, fetch strategies, and bidirectional mapping.
Table of Contents
- Introduction to Association Mappings
- One-to-One Unidirectional Mapping
- Using
@JoinColumnfor Explicit Foreign Key Control - Composite Keys in Associations
- Cascade Types
- Fetch Strategies — Eager vs Lazy Loading
- Handling Lazy Loading Issues
- Data Transfer Objects (DTOs)
- One-to-One Bidirectional Mapping
- Infinite Recursion & How to Fix It
- Summary
1. Introduction to Association Mappings
Overview
In any real-world application, data is rarely stored in a single table. Entities have relationships with each other. JPA (Java Persistence API) and its most popular implementation, Hibernate, provide a set of association mapping annotations to define and manage these relationships between Java entity classes — and by extension, their corresponding database tables.
Types of Associations
| Annotation | Meaning |
|---|---|
@OneToOne | One entity is associated with exactly one other entity |
@OneToMany | One entity is associated with many instances of another |
@ManyToOne | Many entities are associated with one instance of another |
@ManyToMany | Many entities are associated with many instances of another |
Each mapping can also be either:
- Unidirectional — navigation is possible from only one side (parent → child)
- Bidirectional — navigation is possible from both sides (parent ↔ child)
2. One-to-One Unidirectional Mapping
Overview
In a one-to-one unidirectional relationship, one entity holds a reference to exactly one instance of another entity — but only in one direction. The reference exists only from the owning (parent) side to the referenced (child) side. You cannot navigate from the child back to the parent.
Real-World Analogy
Think of a User and their Address. One user has exactly one address. You can look up a user and find their address. But if you have only an address record, there is no built-in way to determine which user it belongs to (unless you navigate back through the parent).
Definition
A one-to-one unidirectional mapping means: one parent entity holds a foreign key reference to one child entity. Navigation is possible only from parent to child.
How It Works in the Database
When you annotate a field with @OneToOne, Hibernate automatically creates a foreign key column in the parent entity's table. This foreign key points to the primary key of the child entity's table.
By default (without @JoinColumn), Hibernate names the foreign key column using the pattern:
1<field_name>_<referenced_primary_key_column>For example, if your field is named userAddress and the referenced entity's primary key is id, Hibernate creates a column named user_address_id in the parent table.
Entity Example (Default Foreign Key Naming)
◆ Parent Entity `UserDetails`
1@Entity2@Table(name = "user_detail")3public class UserDetails {4
5 @Id6 @GeneratedValue(strategy = GenerationType.IDENTITY)7 private Long id;8
9 private String name;10
11 private String phone;12
13 @OneToOne(cascade = CascadeType.ALL)14 private UserAddress userAddress; // Hibernate will create foreign key: user_address_id15
16 // Getters and Setters17}◆ Child Entity `UserAddress`
1@Entity2@Table(name = "user_address")3public class UserAddress {4
5 @Id6 @GeneratedValue(strategy = GenerationType.IDENTITY)7 private Long id;8
9 private String street;10 private String city;11 private String state;12 private String country;13 private String pinCode;14
15 // Getters and Setters16}Resulting Database Tables
user_detail table:
| id | name | phone | user_address_id (FK) |
|---|---|---|---|
| 1 | John | 9999 | 1 |
user_address table:
| id | street | city | state | country | pin_code |
|---|---|---|---|---|---|
| 1 | MG Road | Bangalore | KA | India | 560001 |
user_address_id lives in the parent table (user_detail), not the child. This is the standard behavior for @OneToOne — the owning side holds the foreign key.Diagram
Key Observations
- The
@OneToOneannotation on theuserAddressfield inUserDetailsinstructs JPA to create a foreign key in theuser_detailtable. - Since no
@JoinColumnis specified, Hibernate auto-generates the foreign key column name asuser_address_id. - Navigation from
UserAddressback toUserDetailsis not possible in this unidirectional setup. CascadeType.ALLis used here — this is explained in depth in Section 5.
3. Using `@JoinColumn` for Explicit Foreign Key Control
Why Use `@JoinColumn`?
By default, Hibernate chooses the name for the foreign key column. If you want explicit control over:
- The name of the foreign key column in your table
- The column in the referenced table that the foreign key points to
...then you should use @JoinColumn.
Syntax
1@OneToOne(cascade = CascadeType.ALL)2@JoinColumn(name = "address_id", referencedColumnName = "id")3private UserAddress userAddress;Syntax Breakdown
| Attribute | Meaning |
|---|---|
name | The name of the foreign key column to be created in the current (owning) table |
referencedColumnName | The column in the referenced entity's table that this foreign key points to |
Effect on the Database
user_detail table with @JoinColumn(name = "address_id"):
| id | name | phone | address_id (FK) |
|---|---|---|---|
| 1 | John | 9999 | 1 |
Notice the column is now address_id instead of user_address_id.
Full Example
1@Entity2@Table(name = "user_detail")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 @OneToOne(cascade = CascadeType.ALL)13 @JoinColumn(name = "address_id", referencedColumnName = "id")14 private UserAddress userAddress;15
16 // Getters and Setters17}4. Composite Keys in Associations
Overview
A composite key is a primary key made up of more than one column. When the child entity uses a composite key, you cannot use a single @JoinColumn — you must use @JoinColumns (plural) and specify each part of the composite key.
Setting Up a Composite Key in the Child Entity
◆ Step 1 Create the Embeddable Composite Key Class
1@Embeddable2public class UserAddressCompositeKey implements Serializable {3
4 private String street;5 private String pinCode;6
7 // Getters, Setters, equals(), hashCode()8}◆ Step 2 Use `@EmbeddedId` in the Child Entity
1@Entity2@Table(name = "user_address")3public class UserAddress {4
5 @EmbeddedId6 private UserAddressCompositeKey id; // Composite key: street + pinCode7
8 private String city;9 private String state;10 private String country;11
12 // Getters and Setters13}Resulting user_address table:
| street | pin_code | city | state | country |
|---|---|---|---|---|
| MG Road | 560001 | Bangalore | KA | India |
Both street and pin_code together form the composite primary key.
Referencing a Composite Key from the Parent Entity
Since there are multiple columns in the primary key, you must list all of them using @JoinColumns:
1@Entity2@Table(name = "user_detail")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 @OneToOne(cascade = CascadeType.ALL)13 @JoinColumns({14 @JoinColumn(name = "address_street", referencedColumnName = "street"),15 @JoinColumn(name = "address_pin_code", referencedColumnName = "pinCode")16 })17 private UserAddress userAddress;18
19 // Getters and Setters20}Syntax Breakdown
@JoinColumns— wraps multiple@JoinColumnentries; required when the referenced entity has a composite primary key.- Each
@JoinColumnwithin the array specifies: name— the foreign key column name to create in the current tablereferencedColumnName— the column name in the referenced entity's table
Resulting user_detail table:
| id | name | phone | address_street (FK) | address_pin_code (FK) |
|---|---|---|---|---|
| 1 | John | 9999 | MG Road | 560001 |
@JoinColumns with all the composite key fields listed.Diagram Composite Key Association
5. Cascade Types
Overview
Cascade controls how JPA operations (persist, merge, remove, refresh, detach) performed on a parent entity automatically propagate to its associated child entities.
Why Cascade Exists
Without cascade, you must manage parent and child entity lifecycles manually. This is error-prone when the child entity's existence depends entirely on the parent. For example:
- A
Schoolis deleted → itsRoomrecords should also be deleted. - A
Schoolis created → its associatedRoomrecords should also be created.
When child existence is tightly coupled to the parent, cascade helps enforce this relationship automatically.
Cascade Type Values
| Cascade Type | Trigger | Effect |
|---|---|---|
PERSIST | Insert on parent | Child entity is also inserted |
MERGE | Update on parent | Child entity is also updated |
REMOVE | Delete on parent | Child entity is also deleted |
REFRESH | Refresh on parent | Child entity is also refreshed from DB |
DETACH | Detach on parent | Child entity is also detached from persistence context |
ALL | Any operation | All of the above apply |
CascadeType.PERSIST Insert Propagation
When you save the parent entity, its child entity is automatically saved too.
1@OneToOne(cascade = CascadeType.PERSIST)2@JoinColumn(name = "address_id", referencedColumnName = "id")3private UserAddress userAddress;Example — Controller & Service:
1// Controller2@PostMapping("/user")3public ResponseEntity<UserDetails> saveUser(@RequestBody UserDetails userDetails) {4 return ResponseEntity.ok(userService.saveUser(userDetails));5}6
7// Service8public UserDetails saveUser(UserDetails userDetails) {9 return userDetailsRepository.save(userDetails); // This also saves UserAddress10}Request Body:
1{2 "name": "John",3 "phone": "9999999999",4 "userAddress": {5 "street": "MG Road",6 "city": "Bangalore",7 "state": "Karnataka",8 "country": "India",9 "pinCode": "560001"10 }11}What Happens:
save()is called onuserDetailsRepository.- Internally, Hibernate's Entity Manager calls
persist()onUserDetails. - Because of
CascadeType.PERSIST,persist()is also called on the associatedUserAddress. - Both rows are inserted: one in
user_detail, one inuser_address.
Response:
1{2 "id": 1,3 "name": "John",4 "phone": "9999999999",5 "userAddress": {6 "id": 1,7 "street": "MG Road",8 "city": "Bangalore",9 ...10 }11}CascadeType.MERGE Update Propagation
When you update the parent entity, changes to the child entity are also propagated.
What Happens Without MERGE (only PERSIST configured):
1// PUT request — trying to update both user name and user address city2{3 "id": 1,4 "name": "XYZ_updated",5 "phone": "9999999999",6 "userAddress": {7 "id": 1,8 "city": "Bengaluru" // changed from "Bangalore"9 }10}Result: name updates in user_detail, but city does not update in user_address. Only PERSIST was specified, which handles insert only — not update.
Fix — Add MERGE:
1@OneToOne(cascade = {CascadeType.PERSIST, CascadeType.MERGE})2@JoinColumn(name = "address_id", referencedColumnName = "id")3private UserAddress userAddress;Now both name and city update correctly.
save() in Spring Data JPA calls persist() for new entities (no ID) and merge() for existing entities (ID present). If the passed object has an ID, it routes to an update operation internally.CascadeType.REMOVE Delete Propagation
When you delete the parent entity, the child entity is also deleted.
1@OneToOne(cascade = {CascadeType.PERSIST, CascadeType.MERGE, CascadeType.REMOVE})2@JoinColumn(name = "address_id", referencedColumnName = "id")3private UserAddress userAddress;Delete Controller:
1@DeleteMapping("/user/{id}")2public ResponseEntity<Void> deleteUser(@PathVariable Long id) {3 userService.deleteUser(id);4 return ResponseEntity.noContent().build(); // 204 No Content5}What Happens:
deleteById(id)is called onuserDetailsRepository.- The row is deleted from
user_detail. - Because of
CascadeType.REMOVE, the associatedUserAddressrow is also deleted fromuser_address.
CascadeType.REFRESH Bypassing First-Level Cache
1@OneToOne(cascade = CascadeType.REFRESH)2private UserAddress userAddress;How the Entity Manager works:
JPA's Entity Manager maintains a Persistence Context — an in-memory cache (first-level cache). When you call find() or access an entity, JPA first checks this cache. If found, it returns the cached version without hitting the database.
The EntityManager.refresh() method bypasses this cache and directly queries the database, fetching the freshest data.
What CascadeType.REFRESH does:
When Hibernate internally calls refresh() on a parent entity (for example, to reload fresh data from the database), CascadeType.REFRESH ensures that the child entity is also refreshed directly from the database — not served from the persistence context.
CascadeType.REFRESH and CascadeType.DETACH are rarely used directly by application code. They exist for completeness, and Hibernate may use them internally in certain situations.CascadeType.DETACH Detaching Child Along with Parent
1@OneToOne(cascade = CascadeType.DETACH)2private UserAddress userAddress;Context:
The Persistence Context (managed by the Entity Manager) tracks the lifecycle of entities. An entity inside the persistence context is managed — any changes to it are automatically detected and persisted.
EntityManager.detach(entity) removes an entity from the persistence context. After detachment, JPA no longer tracks that entity's changes.
What CascadeType.DETACH does:
When the parent entity is detached from the persistence context, CascadeType.DETACH ensures that the associated child entity is also detached.
CascadeType.ALL Apply All Operations
Instead of listing each cascade type individually:
1// Verbose approach2@OneToOne(cascade = {CascadeType.PERSIST, CascadeType.MERGE, CascadeType.REMOVE,3 CascadeType.REFRESH, CascadeType.DETACH})Use CascadeType.ALL for convenience:
1@OneToOne(cascade = CascadeType.ALL)2@JoinColumn(name = "address_id", referencedColumnName = "id")3private UserAddress userAddress;Cascade Type Decision Diagram
Summary Table Cascade Types
| Operation | Without Cascade | With Appropriate Cascade |
|---|---|---|
save(parent) | Only parent inserted | Parent + child inserted |
save(parent) (update) | Only parent updated | Parent + child updated |
delete(parent) | Only parent deleted, child remains (FK error risk) | Parent + child deleted |
refresh(parent) | Only parent refreshed from DB | Parent + child refreshed |
detach(parent) | Only parent detached | Parent + child detached |
6. Fetch Strategies Eager vs Lazy Loading
Overview
When you load a parent entity from the database, the question arises: should its associated child entities also be loaded immediately? Or should they be loaded only when explicitly accessed?
JPA provides two fetch strategies:
| Strategy | Behavior |
|---|---|
| Eager Loading | Child entities are loaded immediately when the parent is loaded |
| Lazy Loading | Child entities are loaded on demand — only when your code explicitly accesses them |
Default Fetch Types by Annotation
| Annotation | Default Fetch Type | Reason |
|---|---|---|
@OneToOne | EAGER | One child — minimal performance impact assumed |
@ManyToOne | EAGER | One child — minimal performance impact assumed |
@OneToMany | LAZY | Many children — loading all could be expensive |
@ManyToMany | LAZY | Many children — loading all could be expensive |
@OneToOne and @ManyToOne, there is exactly one child entity. JPA assumes it's likely needed and the cost of fetching one extra row is low. For @OneToMany and @ManyToMany, the number of child records is unknown — it could be thousands. Loading all of them eagerly could cause serious performance issues.How Eager Loading Works Internally (SQL)
With eager loading, Hibernate generates a SELECT with LEFT JOIN query:
1SELECT u.id, u.name, u.phone, a.id, a.street, a.city, a.state, a.country, a.pin_code2FROM user_detail u3LEFT JOIN user_address a ON u.address_id = a.id4WHERE u.id = 1;Everything is fetched in one query. The child data is immediately available.
How Lazy Loading Works Internally (SQL)
With lazy loading, Hibernate first fetches only the parent:
1-- First query: only parent2SELECT u.id, u.name, u.phone, u.address_id3FROM user_detail u4WHERE u.id = 1;Then, only when the child is accessed in code (e.g., userDetail.getUserAddress()), Hibernate fires a second query:
1-- Second query: only when child is accessed2SELECT a.id, a.street, a.city, a.state, a.country, a.pin_code3FROM user_address a4WHERE a.id = 1;Overriding the Default Fetch Type
You can override the default fetch strategy using the fetch attribute:
1@OneToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)2@JoinColumn(name = "address_id", referencedColumnName = "id")3private UserAddress userAddress;This changes the @OneToOne relationship (default EAGER) to use LAZY loading instead.
Similarly, you can make @OneToMany eager:
1@OneToMany(fetch = FetchType.EAGER)2private List<Order> orders;@OneToMany or @ManyToMany EAGER is generally a bad idea in production. If a parent has thousands of children, all of them will be loaded on every parent fetch — a serious performance hazard.Fetch Strategy Comparison Table
| Aspect | Eager Loading | Lazy Loading |
|---|---|---|
| When child is loaded | Immediately with parent | Only when accessed |
| Number of SQL queries | 1 (with JOIN) | 2 (parent first, child on demand) |
| Performance | Good when child always needed | Good when child rarely needed |
| Risk | Loading too much data | LazyInitializationException if session is closed |
Default for @OneToOne | ✅ Yes | Override needed |
Default for @OneToMany | Override needed | ✅ Yes |
7. Handling Lazy Loading Issues
The Problem
When you configure FetchType.LAZY on a @OneToOne relationship and then make a GET request, you may encounter a failure during response serialization.
Scenario:
1@OneToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)2@JoinColumn(name = "address_id", referencedColumnName = "id")3private UserAddress userAddress;GET endpoint:
1@GetMapping("/user/{id}")2public ResponseEntity<UserDetails> getUser(@PathVariable Long id) {3 return ResponseEntity.ok(userService.findById(id));4}What Happens Internally:
findById(id)fires a plain SELECT onuser_detailtable (no JOIN, because ofLAZY).- The
UserDetailsobject is returned withuserAddressas a proxy (not yet loaded from DB). - Jackson (the JSON serializer) starts building the response.
- Jackson tries to serialize the
userAddressfield. - Since
userAddressis a lazy proxy and the database session/persistence context is already closed (new request = new Entity Manager), Jackson cannot trigger another SELECT. - Serialization fails with an error.
userAddress object is created and stored in the same persistence context as userDetails. So when Jackson serializes the response, both objects are still in memory — no extra DB query needed. But during a GET, a new Entity Manager is created, and the persistence context from the insert no longer exists. The lazy proxy cannot load from a closed context.Fix Option 1 `@JsonIgnore`
Add @JsonIgnore on the lazy-loaded field to tell Jackson not to include it in the response at all:
1@JsonIgnore2@OneToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)3@JoinColumn(name = "address_id", referencedColumnName = "id")4private UserAddress userAddress;Result: The userAddress field is excluded from all responses — both for GET and POST. Jackson doesn't attempt to serialize it.
@JsonIgnore removes the field from all serialization contexts — including cases where you actually do want the address data. Use this only when you never want the child in the API response.Fix Option 2 DTO (Recommended)
The better, cleaner, professional approach is to use a Data Transfer Object (DTO). A DTO is a plain Java class that holds only the data you want to expose to the API consumer.
This is covered in detail in Section 8.
8. Data Transfer Objects (DTOs)
Overview
A Data Transfer Object (DTO) is a simple Java class used to carry data between layers of your application. It is separate from your JPA entity and exposes only the fields relevant to a specific API response or request.
Why Use DTOs?
| Problem | Solution via DTO |
|---|---|
| Your entity exposes all DB columns including sensitive/internal ones | DTO exposes only what the client should see |
| Column names in the DB differ from what the API should expose | DTO uses API-friendly field names |
| Lazy loading causes Jackson serialization failures | DTO explicitly controls what to include and triggers lazy loading inside service/mapping layer |
| Circular references in bidirectional mappings | DTO breaks the cycle |
DTO Architecture
Creating a DTO
1public class UserDTO {2
3 private Long userId;4 private String userName;5 private String phoneNumber;6 private String address; // Only the street address — not the full UserAddress object7
8 // Constructor that accepts the entity and maps fields9 public UserDTO(UserDetails userDetails) {10 System.out.println("Going to query user address here now.");11
12 this.userId = userDetails.getId();13 this.userName = userDetails.getName();14 this.phoneNumber = userDetails.getPhone();15
16 // Explicitly access the lazy-loaded child — triggers a SELECT query here17 UserAddress userAddress = userDetails.getUserAddress();18
19 if (userAddress != null) {20 this.address = userAddress.getStreet(); // Only expose street in this DTO21 } else {22 this.address = null;23 }24 }25
26 // Getters27}Adding `toDTO()` to the Entity
1@Entity2@Table(name = "user_detail")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 @OneToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)13 @JoinColumn(name = "address_id", referencedColumnName = "id")14 private UserAddress userAddress;15
16 public UserDTO toDTO() {17 return new UserDTO(this); // Delegates to the DTO constructor18 }19
20 // Getters and Setters21}Using the DTO in the Controller
1@GetMapping("/user/{id}")2public ResponseEntity<UserDTO> getUser(@PathVariable Long id) {3 UserDetails userDetails = userService.findById(id);4 return ResponseEntity.ok(userDetails.toDTO());5}Step-by-Step Execution During GET
What actually happens:
findById(1)fires a plainSELECTonuser_detail— no JOIN because ofLAZY.userDetails.toDTO()is called.- Inside the DTO constructor,
userDetails.getUserAddress()is invoked explicitly. - This triggers a second
SELECTquery onuser_address(Hibernate fires this because the lazy proxy is accessed). - The
UserAddressis loaded, and only thestreetfield is mapped into the DTO. - The DTO (not the entity) is returned to the client — no serialization issues.
DTO Advantages Summary
- You control the API contract independently of the database schema.
- You avoid exposing internal/sensitive fields.
- You solve lazy loading serialization problems cleanly.
- You break circular reference issues in bidirectional mappings.
- Your API can evolve without changing the database and vice versa.
9. One-to-One Bidirectional Mapping
Overview
In a one-to-one bidirectional mapping, both entities hold a reference to each other. Navigation is possible from parent to child and from child back to parent.
Concepts: Owner Side and Inverse Side
| Term | Who | Holds Foreign Key? |
|---|---|---|
| Owner Side | Parent entity | ✅ Yes — foreign key in the DB |
| Inverse Side | Child entity | ❌ No — reference exists only in the Java object |
Implementation
◆ Owner Side `UserDetails` (Parent)
1@Entity2@Table(name = "user_detail")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 // Owner side — holds the foreign key in user_detail table13 @OneToOne(cascade = CascadeType.ALL)14 @JoinColumn(name = "address_id", referencedColumnName = "id")15 private UserAddress userAddress;16
17 // Getters and Setters18}◆ Inverse Side `UserAddress` (Child)
1@Entity2@Table(name = "user_address")3public class UserAddress {4
5 @Id6 @GeneratedValue(strategy = GenerationType.IDENTITY)7 private Long id;8
9 private String street;10 private String city;11 private String state;12 private String country;13 private String pinCode;14
15 // Inverse side — mapped by the field in the owner entity16 // No new foreign key is created in user_address table17 @OneToOne(mappedBy = "userAddress")18 private UserDetails userDetails;19
20 // Getters and Setters21}The `mappedBy` Attribute
1@OneToOne(mappedBy = "userAddress")mappedBy = "userAddress"tells JPA: "The foreign key is already defined on the owner side, in theuserAddressfield of theUserDetailsclass. Do not create a new foreign key here."- This prevents Hibernate from creating an additional foreign key column in
user_address. - The value passed to
mappedBymust match the exact field name on the owner side.
Resulting Database Tables
user_detail table:
| id | name | phone | address_id (FK) |
|---|---|---|---|
| 1 | John | 9999 | 1 |
user_address table:
| id | street | city | state | country | pin_code |
|---|---|---|---|---|---|
| 1 | MG Road | Bangalore | KA | India | 560001 |
Theuser_addresstable has no reference back touser_detailin the database. The bidirectional relationship exists only in Java objects.
Diagram Bidirectional vs Unidirectional
Testing Bidirectional Querying from the Child Side
Controller for UserAddress:
1@GetMapping("/user-address/{id}")2public ResponseEntity<UserAddress> getUserAddress(@PathVariable Long id) {3 return ResponseEntity.ok(userAddressService.findById(id));4}Service:
1public UserAddress findById(Long id) {2 return userAddressRepository.findById(id).orElseThrow();3}What happens when this GET is called:
- JPA queries
user_addressby ID. - Because of the bidirectional mapping, Hibernate generates a
SELECTwithLEFT JOINto also fetch theUserDetailsreferenced byaddress_id.
1SELECT a.*, u.*2FROM user_address a3LEFT JOIN user_detail u ON u.address_id = a.id4WHERE a.id = 1;10. Infinite Recursion & How to Fix It
The Problem
When you query a UserAddress in a bidirectional mapping, Jackson tries to serialize the result:
- Serializes
UserAddress→ encountersuserDetailsfield - Starts serializing
UserDetails→ encountersuserAddressfield - Starts serializing
UserAddressagain → encountersuserDetailsagain - ... infinite loop → Stack Overflow / serialization error
Fix Option 1 `@JsonManagedReference` and `@JsonBackReference`
These two annotations work as a pair to break the cycle:
| Annotation | Used On | Behavior |
|---|---|---|
@JsonManagedReference | Owner/Parent entity (forward reference) | Tells Jackson to serialize this field normally |
@JsonBackReference | Inverse/Child entity (back reference) | Tells Jackson to skip this field during serialization |
◆ Owner Side (`UserDetails`)
1@Entity2public class UserDetails {3
4 @Id5 @GeneratedValue(strategy = GenerationType.IDENTITY)6 private Long id;7
8 private String name;9 private String phone;10
11 @JsonManagedReference // Serialize this field normally12 @OneToOne(cascade = CascadeType.ALL)13 @JoinColumn(name = "address_id", referencedColumnName = "id")14 private UserAddress userAddress;15
16 // Getters and Setters17}◆ Inverse Side (`UserAddress`)
1@Entity2public class UserAddress {3
4 @Id5 @GeneratedValue(strategy = GenerationType.IDENTITY)6 private Long id;7
8 private String street;9 private String city;10 private String state;11 private String country;12 private String pinCode;13
14 @JsonBackReference // Do NOT serialize this field (breaks the cycle)15 @OneToOne(mappedBy = "userAddress")16 private UserDetails userDetails;17
18 // Getters and Setters19}◆ Behavior
GET /user/1 (querying parent):
1{2 "id": 1,3 "name": "John",4 "phone": "9999999999",5 "userAddress": {6 "id": 1,7 "street": "MG Road",8 "city": "Bangalore"9 }10}userAddress is included (managed reference is serialized).
GET /user-address/1 (querying child):
1{2 "id": 1,3 "street": "MG Road",4 "city": "Bangalore",5 "state": "Karnataka",6 "country": "India",7 "pinCode": "560001"8}userDetails is not included (back reference is skipped).
@JsonBackReference is that the child's response never includes the parent data — even if you want it. If you need the parent data from the child's perspective, use @JsonIdentityInfo instead.Fix Option 2 `@JsonIdentityInfo`
@JsonIdentityInfo assigns a unique identifier to each serialized object. Jackson uses this identifier to detect when an object has already been serialized — and instead of recursing, it simply outputs the identifier as a reference.
This approach allows full bidirectional data in responses without infinite recursion.
◆ Owner Side
1@Entity2@JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property = "id")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 @OneToOne(cascade = CascadeType.ALL)13 @JoinColumn(name = "address_id", referencedColumnName = "id")14 private UserAddress userAddress;15
16 // Getters and Setters17}◆ Inverse Side
1@Entity2@JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property = "id")3public class UserAddress {4
5 @Id6 @GeneratedValue(strategy = GenerationType.IDENTITY)7 private Long id;8
9 private String street;10 private String city;11 private String state;12 private String country;13 private String pinCode;14
15 @OneToOne(mappedBy = "userAddress")16 private UserDetails userDetails;17
18 // Getters and Setters19}◆ Annotation Breakdown
1@JsonIdentityInfo(2 generator = ObjectIdGenerators.PropertyGenerator.class, // Use a field value as the unique ID3 property = "id" // Use the "id" field as the unique identifier4)The property must be a unique field in the entity (typically the primary key).
◆ Behavior
GET /user/1 (querying parent):
1{2 "id": 1,3 "name": "John",4 "phone": "9999999999",5 "userAddress": {6 "id": 1,7 "street": "MG Road",8 "city": "Bangalore",9 "userDetails": 1 // Reference by ID only — not re-serialized10 }11}GET /user-address/1 (querying child):
1{2 "id": 1,3 "street": "MG Road",4 "city": "Bangalore",5 "state": "Karnataka",6 "country": "India",7 "pinCode": "560001",8 "userDetails": {9 "id": 1,10 "name": "John",11 "phone": "9999999999",12 "userAddress": 1 // Reference by ID only — not re-serialized13 }14}Jackson serializes each object only once in full. On the second encounter, it outputs only the unique identifier. This breaks the infinite loop while still providing full data from both directions.
Comparison Infinite Recursion Solutions
| Approach | Child can show Parent? | Parent can show Child? | Complexity |
|---|---|---|---|
@JsonIgnore on child ref | ❌ No | ✅ Yes | Simple |
@JsonManagedReference + @JsonBackReference | ❌ No (back ref suppressed) | ✅ Yes | Moderate |
@JsonIdentityInfo | ✅ Yes (via ID reference) | ✅ Yes | Moderate |
| DTO mapping | ✅ Fully controlled | ✅ Fully controlled | Most explicit & recommended |
11. Summary
Key Concepts Recap
Quick Reference Bullets
@OneToOneon a field creates a foreign key in the owning entity's table.- Default foreign key naming by Hibernate:
(e.g.,_ user_address_id). - Use
@JoinColumn(name=..., referencedColumnName=...)for explicit foreign key naming. - Use
@JoinColumns({...})when referencing an entity with a composite key. CascadeType.PERSIST→ insert parent = insert child.CascadeType.MERGE→ update parent = update child.CascadeType.REMOVE→ delete parent = delete child.CascadeType.ALL= all of the above combined.FetchType.EAGER(default for@OneToOne,@ManyToOne) → one JOIN query.FetchType.LAZY(default for@OneToMany,@ManyToMany) → two queries; child loaded on access.- Lazy loading + Jackson serialization = risk of error unless handled with DTO or
@JsonIgnore. mappedByon the inverse side prevents creation of an extra foreign key in the DB.- Bidirectional mappings risk infinite recursion during JSON serialization.
- Fix recursion with:
@JsonManagedReference/@JsonBackReference,@JsonIdentityInfo, or DTOs (recommended).
Interview Notes
- What is the difference between unidirectional and bidirectional mapping?
- Unidirectional: navigation only from parent → child. Bidirectional: navigation from both sides.
- Where does the foreign key get created in a
@OneToOnemapping?
- In the owning entity (the one that has the
@JoinColumnor the plain@OneToOneannotation withoutmappedBy).
- What does
mappedBydo?
- It tells JPA that this side is the inverse side and the foreign key is managed by the named field on the other side. No foreign key column is created on this side.
- What is the difference between
EAGERandLAZYfetch?
EAGER: child loaded with parent in one JOIN query.LAZY: child loaded only when accessed, via a second query.
- What is cascade type and why is it important?
- Cascade propagates operations (insert, update, delete) from parent to child automatically. Without it, child entities must be managed manually.
- What causes infinite recursion in bidirectional mappings and how do you fix it?
- Jackson serializing both sides creates a loop. Fix with
@JsonBackReference,@JsonIdentityInfo, or DTOs.
- Why does lazy loading sometimes fail during serialization?
- The lazy proxy needs an open Hibernate session to fire a query. If the session is closed before Jackson tries to serialize the proxy, it fails. DTO-based mapping is the recommended solution.
- How do you reference a composite key as a foreign key?
- Use
@JoinColumns({@JoinColumn(...), @JoinColumn(...)})and list all the composite key fields explicitly.
End of Chapter — Next: One-to-Many, Many-to-One, Many-to-Many Mappings, Custom Queries, Criteria Queries, Pagination, and Sorting.
Mastery check
How well can you recall this?
Finished this lesson?