🎯 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.)
🏦 Real-world scenario
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.
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.
💰 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.
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
| Feature | JPQL | Native SQL |
|---|---|---|
| Syntax references | Entity class & field names | Table & column names |
| Portability | DB-agnostic (works on H2, PostgreSQL, MySQL) | DB-specific — may break on switch |
| JOIN FETCH | Yes — loads association eagerly | Not available (use manual join) |
| Window functions / JSONB | Not supported | Yes — full SQL power |
| nativeQuery param | Default (false) | nativeQuery = true |
📝 Quiz — 5 questions
Next: Transactions and Rollback →
🎤 Interview Q&A
@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.
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").
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.
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").
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
@OneToMany(mappedBy = "account") on the inverse side.LazyInitializationException. Fix: load what you need within the transaction, or use DTO projections.: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
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 →