Skip to main content
PreparationZone Logo
PrepZone

Associations, Fetch Types, and N+1

One-to-one, one-to-many, and many-to-many mappings, fetch types, and the N+1 query trap.

Pass checkpoint below

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 · Fresher

FetchType.LAZY loads associations on access; EAGER always joins — default lazy on collections reduces surprise query volume.

N+1 problem

L2 · Intermediate

Listing books then accessing author per row triggers N+1 queries — fix with @EntityGraph, join fetch, or DTO queries.

Cascade types

L3 · Advanced

CascadeType.PERSIST on order lines makes sense; REMOVE cascades can delete more than operators expect.

Bidirectional mapping

L4 · Expert

Own the relationship on one side with mappedBy and helper methods to keep both sides consistent — avoids duplicate foreign keys.

Author1
BookN
Order1
Author has many Books. Order has many OrderItems referencing Books.

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:

Java
// 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:

Java
// 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.