🎯 What you will learn

Relational databases are built on foreign keys. JPA lets you model those keys as Java object references — so instead of storing a raw account_id integer you hold an Account account field and let Hibernate manage the join. By the end of this lesson you will understand:

  • @ManyToOne — owning side; FK column lives in this table
  • @OneToMany(mappedBy) — inverse side; no extra column or table
  • FetchType.LAZY vs EAGER and the N+1 query problem
  • Spring Data derived query methods (findByAccountId)
  • JPQL @Query — object-graph syntax, :namedParams, ORDER BY
  • JOIN FETCH to load associations in a single SQL SELECT
  • nativeQuery = true for DB-specific SQL (PostgreSQL window functions, etc.)
💼 Interview reality: "Explain the N+1 problem and how you fix it" appears in virtually every Spring/Hibernate interview. Knowing JOIN FETCH vs lazy loading is the answer interviewers want.

🏦 Real-world scenario

🏦
SouthBank India (Mumbai)
Account → ledger entry relationship

Each SouthBank account has many ledger entries (debits and credits). Arjun maps this @ManyToOne relationship in JPA, writes a JPQL @Query to fetch recent entries for an account, and exposes it as a GET /api/accounts/{accountNo}/ledger endpoint.

🔗 @ManyToOne and @OneToMany mapping

The foreign key account_id column lives in the ledger_entries table — so LedgerEntry is the owning side and carries the @ManyToOne annotation. @JoinColumn names the FK column explicitly so Hibernate doesn't guess.

mvn spring-boot:run
LedgerEntry.javaLesson 29 · @ManyToOne owning side
verified output — startup
:: Spring Boot :: (v3.3.5) INFO --- SouthbankApplication : Started SouthbankApplication in 1.72 seconds

Rule of thumb: The @ManyToOne side always owns the relationship (holds the FK column). Use @OneToMany(mappedBy = "account") on the other side only when you need to navigate the collection — adding it needlessly generates extra SQL and risks N+1 bugs.

📋 LedgerEntryRepository JPQL queries

Spring Data generates SQL from method names automatically. For more control, use @Query with JPQL — which uses entity class names and field paths, not table and column names.

curl -s "http://localhost:8766/api/accounts/SB-100001/ledger"
LedgerEntryRepository.java + AccountController.javaLesson 29 · derived query, @Query JPQL, controller
verified output — two ledger entries for Arjun Sharma[ { "id": 1, "account": { "id": 1, "accountNo": "SB-100001", "holderName": "Arjun Sharma", "balance": 85000.0, "accountType": "SAVINGS", "branch": { "id": 1, "code": "MUM01", "city": "Mumbai", "region": "Maharashtra" }, "createdAt": "2026-04-26T21:01:16.582733" }, "type": "CREDIT", "amount": 10000.0, "description": "Salary deposit", "createdAt": "2026-04-26T21:01:16.583242" }, { "id": 2, "account": { "id": 1, "accountNo": "SB-100001", "holderName": "Arjun Sharma", "balance": 85000.0, "accountType": "SAVINGS", "branch": { "id": 1, "code": "MUM01", "city": "Mumbai", "region": "Maharashtra" }, "createdAt": "2026-04-26T21:01:16.582733" }, "type": "DEBIT", "amount": 2500.0, "description": "ATM withdrawal", "createdAt": "2026-04-26T21:01:16.583242" } ]

💰 High-value accounts (JPQL @Query)

JPQL can filter by balance, join across relationships, and use native SQL for database-specific features. JOIN FETCH is the key technique to avoid the N+1 problem when you need both an entity and its association.

curl -s "http://localhost:8766/api/accounts/high-value?min=100000"
AccountRepository.javaLesson 29 · JPQL @Query, nativeQuery, JOIN FETCH
verified output — accounts with balance ≥ ₹1,00,000[ { "id": 2, "accountNo": "SB-100002", "holderName": "Priya Mehta", "balance": 210000.0, "accountType": "CURRENT", "branch": { "id": 1, "code": "MUM01", "city": "Mumbai", "region": "Maharashtra" }, "createdAt": "2026-04-26T21:01:16.582733" }, { "id": 4, "accountNo": "SB-100004", "holderName": "Deepa Nair", "balance": 125000.0, "accountType": "SAVINGS", "branch": { "id": 3, "code": "BLR01", "city": "Bangalore", "region": "Karnataka" }, "createdAt": "2026-04-26T21:01:16.582733" } ]

N+1 in plain English: Fetching 100 accounts lazily then accessing account.getBranch() in a loop fires 1 + 100 = 101 SQL queries. JOIN FETCH collapses this to 1 query. Always load associations with JOIN FETCH when you know you'll need them.

📋 JPQL vs native SQL — quick reference

FeatureJPQLNative SQL
Syntax referencesEntity class & field namesTable & column names
PortabilityDB-agnostic (works on H2, PostgreSQL, MySQL)DB-specific — may break on switch
JOIN FETCHYes — loads association eagerlyNot available (use manual join)
Window functions / JSONBNot supportedYes — full SQL power
nativeQuery paramDefault (false)nativeQuery = true

📝 Quiz — 5 questions

Question 1 of 5
What annotation models a many-to-one relationship in JPA?
Question 2 of 5
What does FetchType.LAZY do?
Question 3 of 5
What is the N+1 query problem?
Question 4 of 5
How do you write a JPQL query that joins Account with Branch?
Question 5 of 5
When is nativeQuery = true appropriate?
0
/ 5
Quiz complete!

Next: Transactions and Rollback →

🎤 Interview Q&A

EasyWhat is the difference between @OneToMany and @ManyToOne?
+

@ManyToOne: the owning side; the FK column lives in this table (e.g., account_id in ledger_entries). @OneToMany: the inverse side; a collection of related entities. Always put the FK on the @ManyToOne side and use mappedBy on the @OneToMany.

EasyWhat does @JoinColumn do?
+

It specifies the name of the foreign key column in the table. Without it, Hibernate generates a column name from the field and target entity names — often ugly. Always name it explicitly: @JoinColumn(name = "account_id").

MediumHow do you prevent Jackson from serialising a circular @OneToMany back-reference?
+

Annotate one side with @JsonManagedReference and the other with @JsonBackReference. Or use @JsonIgnore on the back-reference. Best practice: use DTOs that don't have cycles — Jackson never sees the entity directly.

MediumHow do you sort results in a derived query method?
+

Append OrderBy to the method name: findByAccountTypeOrderByBalanceDesc(String type). Or pass a Sort parameter: findByAccountType(String type, Sort sort) and call with Sort.by(Sort.Direction.DESC, "balance").

HardHow does Hibernate decide which SQL JOIN type to use for @ManyToOne with LAZY?
+

Hibernate uses a "proxy" for LAZY @ManyToOne. The proxy is a ByteBuddy subclass of the target entity with only the ID set. When you access any other field, Hibernate fires a SELECT by primary key. For JOIN FETCH in JPQL, Hibernate emits an INNER JOIN or LEFT JOIN depending on @JoinColumn(nullable) — nullable=false → INNER JOIN; nullable=true → LEFT JOIN.

⚠️ Common mistakes

Bidirectional @OneToMany without mappedBy
Creates a join table instead of using the existing FK. Always use @OneToMany(mappedBy = "account") on the inverse side.
Accessing LAZY associations outside a transaction
Once the EntityManager closes (after the service method returns), any LAZY field access throws LazyInitializationException. Fix: load what you need within the transaction, or use DTO projections.
Using EAGER on @OneToMany collections
EAGER on a collection runs a SELECT * per parent entity. On a list of 1000 accounts this means 1001 queries. Always LAZY on collections; load with JOIN FETCH when needed.
Missing @Param name matching @Query parameter
If @Query uses :accountId but @Param says "acctId", the binding fails at runtime with ParameterNotFound. Keep names consistent.

✅ Key takeaways

  • @ManyToOne + @JoinColumn maps foreign keys to object references
  • FetchType.LAZY avoids unnecessary JOINs; use JOIN FETCH when you need the related entity
  • JPQL uses entity class names and field paths, not table/column names
  • N+1 problem: load collections with JOIN FETCH, not lazy-loading in a loop
  • nativeQuery=true for DB-specific SQL that JPQL can't express
Africa & India's Best AI Academy
🤖 AI-first 🎓 Placement Assistance

From JPA relations to production REST APIs

Join the Best AI Programs — three 5-month courses, fully online, with placement assistance. Week 1 is free.

Explore our AI-era courses →