JPA Interview Questions & Best Examples

Java Persistence API • Spring Data JPA • Pagination • Performance • Transactions

JPA (Jakarta Persistence API) is a specification for mapping Java objects to relational database tables. Hibernate is one of the most popular implementations. This guide focuses on practical interview questions, small examples, pagination, performance issues, and real-world scenarios.

1. JPA Interview Topics at a Glance

#TopicWhat to Know
1JPA vs HibernateJPA is a specification; Hibernate is an implementation.
2EntityJava class mapped to a database table using @Entity.
3Persistence ContextManages entity state and provides first-level caching.
4Entity LifecycleTransient/New, Managed, Detached and Removed.
5persist vs mergeUnderstand new entities versus detached entity state.
6Dirty CheckingAutomatic detection and synchronization of changes to managed entities.
7Relationships@OneToOne, @OneToMany, @ManyToOne, @ManyToMany.
8Lazy vs EagerUnderstand when related data is loaded.
9N+1 ProblemRecognize and solve excessive relationship queries.
10Cascade & orphanRemovalUnderstand operation propagation and child deletion.
11JPQLQuery entities and entity attributes.
12PaginationPage, Slice, offset pagination and keyset pagination.
13TransactionsUse @Transactional to define transaction boundaries.
14LockingOptimistic and pessimistic locking.
15CachingFirst-level and second-level cache concepts.

2. What is JPA?

JPA — Jakarta Persistence API

JPA provides a standard programming model for mapping Java objects to relational database tables.

Java Application
      |
      v
     JPA
      |
      v
Hibernate / EclipseLink
      |
      v
   Database
Interview answer: JPA is a specification, while Hibernate is a popular implementation of that specification.

3. Entity Example

@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.

4. Persistence Context

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;
Interview point: Persistence Context manages entity state and provides first-level caching.

5. Entity Lifecycle

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

6. persist() vs merge()

persist()

Employee employee = new Employee();
employee.setName("John");

entityManager.persist(employee);

Typically used for a new entity: NEW → MANAGED.

merge()

Employee managedEmployee =
    entityManager.merge(detachedEmployee);
Important: merge() returns a managed instance. The original detached object does not itself become managed.

7. Dirty Checking

@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.

8. JPA Relationships

  • @OneToOne — one entity to one entity
  • @OneToMany — one entity to many entities
  • @ManyToOne — many entities to one entity
  • @ManyToMany — many entities to many entities

9. @ManyToOne — Practical Example

@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

10. @OneToMany & Owning Side

@OneToMany(mappedBy = "department")
private List<Employee> employees;

The relationship is controlled by:

@ManyToOne
@JoinColumn(name = "department_id")
private Department department;
Interview rule: In a typical bidirectional relationship, the side with @JoinColumn is the owning side. mappedBy indicates the inverse side.

11. Lazy vs Eager Loading

@OneToMany(fetch = FetchType.LAZY)
private List<Employee> employees;

@ManyToOne(fetch = FetchType.EAGER)
private Department department;
LAZYEAGER
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.

12. N+1 Query Problem ⭐

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;
...

Possible solution: JOIN FETCH

@Query("""
    SELECT DISTINCT d
    FROM Department d
    JOIN FETCH d.employees
""")
List<Department> findDepartmentsWithEmployees();
Interview point: Always consider the result size and query shape when using fetch joins.

13. Cascade Types

@OneToMany(
    mappedBy = "department",
    cascade = CascadeType.ALL
)
private List<Employee> employees;

Common cascade types:

  • PERSIST
  • MERGE
  • REMOVE
  • REFRESH
  • DETACH
  • ALL
Cascade ≠ FetchType: Cascade controls operation propagation; FetchType controls loading behavior.

14. Cascade REMOVE vs orphanRemoval

@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);

15. JPQL

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
);

16. JPQL vs Native Query

JPQL

@Query("""
    SELECT e
    FROM Employee e
    WHERE e.name = :name
""")

Native SQL

@Query(
    value = """
        SELECT *
        FROM employees
        WHERE name = :name
    """,
    nativeQuery = true
)
Interview answer: JPQL queries the entity model and is generally database-independent; native queries use SQL understood by the database.

17. Pagination in Spring Data JPA ⭐⭐⭐⭐⭐

Repository

public interface EmployeeRepository
        extends JpaRepository<Employee, Long> {
}

Service

public Page<Employee> getEmployees(
        int page,
        int size) {

    Pageable pageable =
        PageRequest.of(page, size);

    return employeeRepository.findAll(pageable);
}

Controller

@GetMapping("/employees")
public Page<Employee> getEmployees(
        @RequestParam(defaultValue = "0") int page,
        @RequestParam(defaultValue = "10") int size) {

    return employeeService.getEmployees(page, size);
}

Requests

GET /employees?page=0&size=10
GET /employees?page=1&size=10
GET /employees?page=2&size=10

18. How Offset Pagination Works

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;
PageApproximate records
01–10
111–20
221–30
Best practice: Use a deterministic ORDER BY for stable pagination.

19. Pagination with Sorting

Pageable pageable =
    PageRequest.of(
        page,
        size,
        Sort.by("name").ascending()
    );

Page<Employee> result =
    employeeRepository.findAll(pageable);

20. Pagination with a Custom Query

@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);

21. Page vs Slice ⭐⭐⭐⭐

PageSlice
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.

22. Offset vs Keyset Pagination ⭐⭐⭐⭐⭐

Offset

SELECT *
FROM employees
ORDER BY id
LIMIT 20 OFFSET 100000;

Simple and supports direct page-number navigation, but very large offsets can become expensive.

Keyset / Seek Pagination

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
Interview answer: Keyset pagination is often better for very large datasets when the user moves sequentially through results.

23. Pagination Best Practice

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()
    );
  • Validate page and page size.
  • Set a maximum page size.
  • Use deterministic sorting.
  • For huge datasets, evaluate keyset pagination.
  • Return only the fields required by the API when appropriate, using DTO projections.

24. @Transactional

@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.

25. save() vs saveAndFlush()

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.
Remember: Flush is not the same as transaction commit.

26. flush() vs commit()

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.

27. Optimistic Locking

@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
Use case: Useful when concurrent conflicts are possible but database row locks are not desirable for every read.

28. Pessimistic Locking

@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.

29. First-Level vs Second-Level Cache

Application
   |
   +-- EntityManager 1
   |
   +-- EntityManager 2
   |
   +-- EntityManager 3
            |
            v
     Second-Level Cache
            |
            v
         Database
First-Level CacheSecond-Level Cache
Associated with persistence context/EntityManager.Shared across persistence contexts within the persistence setup.
Built into JPA persistence-context behavior.Provider/configuration dependent.

30. @Embedded vs @Entity

@Entity

@Entity
class Address {

    @Id
    private Long id;
}

Has its own identity and lifecycle.

@Embeddable

@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.

31. Top JPA Interview Questions

PriorityInterview 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().

⭐ Final Interview Revision — One-Line Answers

ConceptQuick Answer
JPASpecification for persistence/ORM.
HibernatePopular JPA implementation.
EntityJava object mapped to a database table.
Persistence ContextManages entity state and provides first-level cache.
Dirty CheckingAutomatically detects changes to managed entities.
LAZYLoads associated data when accessed.
EAGERRequests associated data immediately according to the mapping/provider.
CascadePropagates selected entity operations.
orphanRemovalCan delete a child removed from an orphan-removal relationship.
JPQLQueries entities and their attributes.
Native SQLQueries the database directly using SQL.
PagePagination result with total-count/page information.
SlicePagination result focused on whether another slice exists.
OffsetUses page offset, commonly LIMIT + OFFSET.
KeysetUses the last-seen key to fetch the next results.
@VersionUsed for optimistic locking.
flush()Synchronizes pending persistence-context changes with the database.
commit()Completes the transaction.