Java Persistence API • Spring Data JPA • Pagination • Performance • Transactions
| # | Topic | What to Know |
|---|---|---|
| 1 | JPA vs Hibernate | JPA is a specification; Hibernate is an implementation. |
| 2 | Entity | Java class mapped to a database table using @Entity. |
| 3 | Persistence Context | Manages entity state and provides first-level caching. |
| 4 | Entity Lifecycle | Transient/New, Managed, Detached and Removed. |
| 5 | persist vs merge | Understand new entities versus detached entity state. |
| 6 | Dirty Checking | Automatic detection and synchronization of changes to managed entities. |
| 7 | Relationships | @OneToOne, @OneToMany, @ManyToOne, @ManyToMany. |
| 8 | Lazy vs Eager | Understand when related data is loaded. |
| 9 | N+1 Problem | Recognize and solve excessive relationship queries. |
| 10 | Cascade & orphanRemoval | Understand operation propagation and child deletion. |
| 11 | JPQL | Query entities and entity attributes. |
| 12 | Pagination | Page, Slice, offset pagination and keyset pagination. |
| 13 | Transactions | Use @Transactional to define transaction boundaries. |
| 14 | Locking | Optimistic and pessimistic locking. |
| 15 | Caching | First-level and second-level cache concepts. |
JPA provides a standard programming model for mapping Java objects to relational database tables.
Java Application
|
v
JPA
|
v
Hibernate / EclipseLink
|
v
Database
@Entity
@Table(name = "employees")
public class Employee {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private String department;
// getters and setters
}
The @Entity class represents a database table and its fields are mapped to columns.
The persistence context is a set of managed entity instances. It also acts as the JPA first-level cache.
Employee employee =
entityManager.find(Employee.class, 101L);
employee.setName("John");
At flush/commit, dirty checking can detect the change and synchronize it with the database.
UPDATE employees SET name = 'John' WHERE id = 101;
NEW | | persist() v MANAGED | \ | \ remove() | v | REMOVED | | detach() v DETACHED
Employee employee = new Employee(); // NEW
entityManager.persist(employee); // MANAGED
employee.setName("John");
entityManager.detach(employee); // DETACHED
Employee employee = new Employee();
employee.setName("John");
entityManager.persist(employee);
Typically used for a new entity: NEW → MANAGED.
Employee managedEmployee =
entityManager.merge(detachedEmployee);
merge() returns a managed instance. The original detached object does not itself become managed.@Transactional
public void updateEmployee(Long id) {
Employee emp =
employeeRepository.findById(id)
.orElseThrow();
emp.setName("Rahul");
}
No explicit update call is required for the managed entity. JPA can detect the changed state and flush it to the database.
@OneToOne — one entity to one entity@OneToMany — one entity to many entities@ManyToOne — many entities to one entity@ManyToMany — many entities to many entities@Entity
public class Department {
@Id
@GeneratedValue
private Long id;
private String name;
}
@Entity
public class Employee {
@Id
@GeneratedValue
private Long id;
private String name;
@ManyToOne
@JoinColumn(name = "department_id")
private Department department;
}
Database relationship:
employees ------------------------- id name department_id ---> department.id
@OneToMany(mappedBy = "department") private List<Employee> employees;
The relationship is controlled by:
@ManyToOne @JoinColumn(name = "department_id") private Department department;
@JoinColumn is the owning side. mappedBy indicates the inverse side.@OneToMany(fetch = FetchType.LAZY) private List<Employee> employees; @ManyToOne(fetch = FetchType.EAGER) private Department department;
| LAZY | EAGER |
|---|---|
| Related data is loaded when accessed. | Related data is requested immediately according to the mapping/provider. |
| Usually preferred for large collections. | Can cause unnecessary data loading if used carelessly. |
If one query loads departments and then each department triggers another query for employees, the application may execute approximately 1 + N queries.
SELECT * FROM department; SELECT * FROM employee WHERE department_id = 1; SELECT * FROM employee WHERE department_id = 2; SELECT * FROM employee WHERE department_id = 3; ...
@Query("""
SELECT DISTINCT d
FROM Department d
JOIN FETCH d.employees
""")
List<Department> findDepartmentsWithEmployees();
@OneToMany(
mappedBy = "department",
cascade = CascadeType.ALL
)
private List<Employee> employees;
Common cascade types:
PERSISTMERGEREMOVEREFRESHDETACHALL@OneToMany(
mappedBy = "department",
orphanRemoval = true
)
private List<Employee> employees;
With orphan removal, removing a child from the relationship can cause that child to be deleted when the persistence context is flushed.
department.getEmployees().remove(employee);
JPQL works with entity names and entity attributes rather than database table/column names.
@Query("""
SELECT e
FROM Employee e
WHERE e.department.name = :department
""")
List<Employee> findByDepartment(
@Param("department") String department
);
@Query("""
SELECT e
FROM Employee e
WHERE e.name = :name
""")
@Query(
value = """
SELECT *
FROM employees
WHERE name = :name
""",
nativeQuery = true
)
public interface EmployeeRepository
extends JpaRepository<Employee, Long> {
}
public Page<Employee> getEmployees(
int page,
int size) {
Pageable pageable =
PageRequest.of(page, size);
return employeeRepository.findAll(pageable);
}
@GetMapping("/employees")
public Page<Employee> getEmployees(
@RequestParam(defaultValue = "0") int page,
@RequestParam(defaultValue = "10") int size) {
return employeeService.getEmployees(page, size);
}
GET /employees?page=0&size=10 GET /employees?page=1&size=10 GET /employees?page=2&size=10
For:
page = 2 size = 10
The offset is:
offset = page × size
= 2 × 10
= 20
Conceptually, a database may execute a query similar to:
SELECT * FROM employees ORDER BY id LIMIT 10 OFFSET 20;
| Page | Approximate records |
|---|---|
| 0 | 1–10 |
| 1 | 11–20 |
| 2 | 21–30 |
ORDER BY for stable pagination.Pageable pageable =
PageRequest.of(
page,
size,
Sort.by("name").ascending()
);
Page<Employee> result =
employeeRepository.findAll(pageable);
@Query("""
SELECT e
FROM Employee e
WHERE e.department.name = :department
""")
Page<Employee> findByDepartment(
@Param("department") String department,
Pageable pageable
);
Pageable pageable =
PageRequest.of(0, 10);
Page<Employee> employees =
repository.findByDepartment("IT", pageable);
| Page | Slice |
|---|---|
| Provides page content plus total elements/pages. | Provides content and whether another slice is available. |
| Useful when UI needs total pages/records. | Useful for next-page/infinite-scroll style navigation. |
| Often involves a count query. | Can avoid the total-count query. |
SELECT * FROM employees ORDER BY id LIMIT 20 OFFSET 100000;
Simple and supports direct page-number navigation, but very large offsets can become expensive.
SELECT * FROM employees WHERE id > 125 ORDER BY id LIMIT 20;
If the last item from the previous response has id = 125, the next request starts after that key.
First request: WHERE id > 0 LIMIT 20 Next request: WHERE id > 125 LIMIT 20 Next request: WHERE id > 150 LIMIT 20
if (page < 0) {
throw new IllegalArgumentException("Invalid page");
}
if (size <= 0 || size > 100) {
throw new IllegalArgumentException("Invalid page size");
}
Pageable pageable =
PageRequest.of(
page,
size,
Sort.by("id").ascending()
);
@Transactional
public void transferMoney(
Long fromId,
Long toId,
BigDecimal amount) {
Account from =
accountRepository.findById(fromId)
.orElseThrow();
Account to =
accountRepository.findById(toId)
.orElseThrow();
from.debit(amount);
to.credit(amount);
}
@Transactional defines the transaction boundary. JPA changes are synchronized with the database as part of the transaction lifecycle.
repository.save(employee); repository.saveAndFlush(employee);
| save() | saveAndFlush() |
|---|---|
| Persists/merges through the persistence context. | Persists/merges and requests an immediate flush. |
| SQL need not execute immediately. | Flushes pending changes to the database. |
flush() → Synchronize persistence-context changes with DB commit() → Complete the transaction
A flush can occur before transaction commit, and a flush itself does not mean the transaction has successfully committed.
@Entity
public class Employee {
@Id
private Long id;
private String name;
@Version
private Long version;
}
JPA uses the version field to detect conflicting updates.
User A → version 5 → update → version 6
User B → still has version 5
→ update conflicts
→ optimistic locking failure
@Lock(LockModeType.PESSIMISTIC_WRITE) Optional<Employee> findById(Long id);
Pessimistic locking asks the database to lock the relevant row/resource so conflicting transactions cannot freely modify it concurrently, subject to the database and transaction configuration.
Application
|
+-- EntityManager 1
|
+-- EntityManager 2
|
+-- EntityManager 3
|
v
Second-Level Cache
|
v
Database
| First-Level Cache | Second-Level Cache |
|---|---|
| Associated with persistence context/EntityManager. | Shared across persistence contexts within the persistence setup. |
| Built into JPA persistence-context behavior. | Provider/configuration dependent. |
@Entity
class Address {
@Id
private Long id;
}
Has its own identity and lifecycle.
@Embeddable
class Address {
private String city;
private String state;
}
@Entity
class Employee {
@Id
private Long id;
@Embedded
private Address address;
}
An embeddable is value-like data stored as part of its owning entity and has no independent entity identity.
| Priority | Interview Question |
|---|---|
| ★★★★★ | What is JPA vs Hibernate? |
| ★★★★★ | What is Persistence Context? |
| ★★★★★ | Explain entity lifecycle. |
| ★★★★★ | persist() vs merge() |
| ★★★★★ | What is dirty checking? |
| ★★★★★ | Lazy vs Eager loading. |
| ★★★★★ | Explain the N+1 problem. |
| ★★★★★ | How do you solve N+1? |
| ★★★★★ | Explain @OneToMany / @ManyToOne. |
| ★★★★★ | What is the owning side? |
| ★★★★★ | Cascade vs orphanRemoval. |
| ★★★★★ | JPQL vs Native Query. |
| ★★★★★ | Explain pagination in Spring Data JPA. |
| ★★★★★ | Page vs Slice. |
| ★★★★★ | Offset vs Keyset pagination. |
| ★★★★☆ | First-level vs Second-level cache. |
| ★★★★☆ | Optimistic vs Pessimistic locking. |
| ★★★★☆ | save() vs saveAndFlush(). |
| ★★★★☆ | flush() vs commit(). |
| ★★★★☆ | What is @Transactional? |
| ★★★☆☆ | @Embedded vs @Entity. |
| ★★★☆☆ | find() vs getReference(). |
| Concept | Quick Answer |
|---|---|
| JPA | Specification for persistence/ORM. |
| Hibernate | Popular JPA implementation. |
| Entity | Java object mapped to a database table. |
| Persistence Context | Manages entity state and provides first-level cache. |
| Dirty Checking | Automatically detects changes to managed entities. |
| LAZY | Loads associated data when accessed. |
| EAGER | Requests associated data immediately according to the mapping/provider. |
| Cascade | Propagates selected entity operations. |
| orphanRemoval | Can delete a child removed from an orphan-removal relationship. |
| JPQL | Queries entities and their attributes. |
| Native SQL | Queries the database directly using SQL. |
| Page | Pagination result with total-count/page information. |
| Slice | Pagination result focused on whether another slice exists. |
| Offset | Uses page offset, commonly LIMIT + OFFSET. |
| Keyset | Uses the last-seen key to fetch the next results. |
| @Version | Used for optimistic locking. |
| flush() | Synchronizes pending persistence-context changes with the database. |
| commit() | Completes the transaction. |