Why this matters
- BookStore has authors, books, and orders — relationships are unavoidable in any real domain model.
- Eager fetching loads everything upfront; lazy fetching defers until accessed — each has trade-offs.
- The N+1 problem is the most common JPA performance bug in production APIs.
Lazy vs eager
L1 · FresherFetchType.LAZY loads associations on access; EAGER always joins — default lazy on collections reduces surprise query volume.
N+1 problem
L2 · IntermediateListing books then accessing author per row triggers N+1 queries — fix with @EntityGraph, join fetch, or DTO queries.
Cascade types
L3 · AdvancedCascadeType.PERSIST on order lines makes sense; REMOVE cascades can delete more than operators expect.
Bidirectional mapping
L4 · ExpertOwn the relationship on one side with mappedBy and helper methods to keep both sides consistent — avoids duplicate foreign keys.
One-to-one
A book has one inventory row. Unidirectional mapping puts the foreign key on the owner and does not give Inventory a field back to Book:
// learn:fragment
@Entity
public class Book {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@OneToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL, orphanRemoval = true)
@JoinColumn(name = "inventory_id", unique = true)
private Inventory inventory;
}
@Entity
public class Inventory {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private int stock;
}
Bidirectional mapping adds the inverse side. mappedBy names the field on Book that already owns the foreign key, so Hibernate does not create a second column:
// learn:fragment
@Entity
public class Inventory {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private int stock;
@OneToOne(mappedBy = "inventory", fetch = FetchType.LAZY)
private Book book;
}
Keep both sides in sync with a helper (book.setInventory also sets inventory.book). Lazy @OneToOne often still loads the target unless bytecode enhancement is enabled, because the owner must know whether the foreign key is null. If you do not navigate from inventory back to book in the same request, leave the association unidirectional.
The rest of this guide is part of Pro
Free covers every fresher guide in full. Pro unlocks Senior, Staff and Architect guides across every track.
Still to come · 6 sections
- One-to-many: Author and Books
- FetchType: LAZY vs EAGER
- The N+1 problem
- Many-to-many: Books and Tags
- DTO projection to avoid over-fetching
- Cascade types
Test yourself
Answer these before moving on — recall is what makes it stick.