Relationships, JPQL, Fetching & Real-World Tradeoffs
Relationships & Fetch Strategy
@Entity
public class Customer {
@OneToMany(mappedBy = "customer", fetch = FetchType.LAZY)
private List<Order> orders;
}@OneToMany/@ManyToOne/@ManyToMany express relational associations in the object model, with JPA handling the underlying foreign keys and joins. LAZY fetching defers loading related data until actually accessed — good for avoiding unneeded queries, but looping over parents and lazily accessing each one's collection triggers the classic N+1 query problem (N+1 total queries instead of one combined query).
JPQL & the N+1 Fix
SELECT c FROM Customer c JOIN FETCH c.orders WHERE c.active = trueJPQL is object-oriented — queries reference entity classes and fields, not table/column names directly, keeping application code focused on the domain model. JOIN FETCH explicitly eager-loads a relationship within a single query, the standard query-level fix for N+1.
Transactions, Cascading & Optimistic Locking
@Transactional ensures a group of operations commits together or rolls back together, never partially applying. cascade = CascadeType.ALL propagates operations (persist, remove) from a parent to its related children automatically. A @Version field implements optimistic locking — an update fails if the version changed since load, catching a concurrent modification rather than silently overwriting it.
Escape Hatches & Spring Data JPA
The Criteria API offers a type-safe, programmatic alternative to string-based JPQL, catching field-reference typos at compile time. Native SQL (nativeQuery = true) is the escape hatch for queries or DB-specific features JPQL can't cleanly express. Spring Data JPA adds a further convenience layer, auto-generating repository implementations from interface method signatures — a common, highly productive combination in Spring Boot apps. The convenience of ORM-generated SQL trades some direct control; profiling generated queries and selectively hand-tuning hot paths is the standard mitigation for performance-critical code.
Keep your own version of these notes — editable, searchable, and organised by your stack.
Start free