Performance: Why relationships matter in JPA
This affects database query performance and page load speed by controlling how related data is fetched and rendered.
Jump into concepts and practice - no test required
class Order {
@OneToMany(fetch = FetchType.LAZY)
List<Item> items;
}
// Items load only when accessed, reducing initial query sizeclass Order { @OneToMany(fetch = FetchType.EAGER) List<Item> items; } // Fetching orders triggers loading all items immediately, even if not needed
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Eager fetching all relationships | N/A (backend data) | N/A | Blocks rendering due to slow data arrival | [X] Bad |
| Lazy fetching with selective joins | N/A (backend data) | N/A | Faster data arrival, smoother rendering | [OK] Good |
Book and accessing its author.getName()?@Entity
class Book {
@Id
Long id;
String title;
@ManyToOne
Author author;
}
@Entity
class Author {
@Id
Long id;
String name;
}@Entity
class Order {
@Id
Long id;
@OneToMany
Customer customer;
}Student and Course. A student can enroll in many courses, and a course can have many students. Which JPA relationship setup correctly models this, and why is it important to define it properly?