Full Stack • Java • System Design • Cloud • AI Engineering

JPA Interview Questions and Answers

Top 75 JPA interview questions and answers covering EntityManager, Persistence Context, Entity Lifecycle, JPQL, Criteria API, Transactions, Caching, Locking, Performance"

Introduction

JPA interviews usually focus on:

Core JPA Concepts

Entity Lifecycle

Persistence Context

EntityManager

JPQL

Transactions

Locking

Caching

Performance Tuning

Spring Data JPA

JPA Fundamentals


1. What is JPA?

JPA stands for:

Java Persistence API

It is a specification that defines how Java objects should be persisted in relational databases.

JPA itself is not an implementation.

Popular implementations:

Hibernate

EclipseLink

OpenJPA

2. Why was JPA introduced?

Before JPA:

Hibernate APIs

TopLink APIs

Vendor-specific code

Problems:

Vendor lock-in

No standard API

JPA introduced:

Standard Persistence Specification

3. Difference between JPA and Hibernate?

JPA Hibernate
Specification Implementation
Defines APIs Implements APIs
Vendor Neutral Hibernate Specific
EntityManager Session

Example:

EntityManager entityManager;

JPA.

Session session;

Hibernate.


4. What are the main JPA components?

Entity

EntityManager

Persistence Context

EntityManagerFactory

JPQL

Transactions

5. What is ORM?

ORM means:

Object Relational Mapping

Maps:

Class → Table

Object → Row

Field → Column

Entity Questions


6. What is an Entity?

An entity is a Java class mapped to a database table.

Example:

@Entity
@Table(name = "employees")
public class Employee {

    @Id
    private Long id;

    private String name;
}

7. What are requirements of an Entity?

Must have:

@NoArgsConstructor

Primary Key

@Entity Annotation

Recommended:

Serializable

Equals & HashCode

8. Difference between @Entity and @Table?

@Entity

Marks class as JPA entity.

@Entity

@Table

Maps table name.

@Table(name = "employees")

9. What is @Id?

Defines primary key.

@Id
private Long id;

10. What is @GeneratedValue?

Generates primary key values.

@GeneratedValue
private Long id;

Primary Key Strategies


11. Explain GenerationType.IDENTITY

@GeneratedValue(strategy = GenerationType.IDENTITY)

Database generates ID.

Example:

AUTO_INCREMENT

12. Explain GenerationType.SEQUENCE

@GeneratedValue(strategy = GenerationType.SEQUENCE)

Uses sequence object.

Best for batching.


13. Explain GenerationType.TABLE

Uses separate table for IDs.

Rarely used.


14. Explain GenerationType.AUTO

Provider decides strategy.


Entity Lifecycle


15. Explain Entity Lifecycle States

Transient

Managed

Detached

Removed

16. What is Transient State?

Employee employee =
        new Employee();

Not managed.

Not stored in DB.


17. What is Managed State?

entityManager.persist(employee);

Tracked by JPA.

Dirty checking active.


18. What is Detached State?

entityManager.detach(employee);

No longer tracked.


19. What is Removed State?

entityManager.remove(employee);

Marked for deletion.


20. Lifecycle Diagram

stateDiagram-v2

[*] --> Transient

Transient --> Managed : persist

Managed --> Detached : detach

Detached --> Managed : merge

Managed --> Removed : remove

Removed --> [*]

EntityManager


21. What is EntityManager?

Main JPA interface used for:

persist

find

merge

remove

flush

clear

detach

refresh

22. What is EntityManagerFactory?

Factory used to create EntityManager instances.

Heavyweight object.

Usually singleton.


23. Difference between EntityManager and EntityManagerFactory?

EntityManager EntityManagerFactory
Lightweight Heavyweight
Per Transaction Application Scope
Performs CRUD Creates EntityManager

24. What does persist() do?

Makes entity managed.

Schedules INSERT.

entityManager.persist(employee);

25. What does merge() do?

Reattaches detached entity.

entityManager.merge(employee);

Returns managed copy.


26. Difference between persist and merge?

persist merge
New Entity Detached Entity
Insert Update
Same Object Managed Returns Managed Copy

27. What does flush() do?

Synchronizes persistence context with database.

entityManager.flush();

28. Difference between flush and commit?

flush

Executes SQL

commit

Makes Transaction Permanent

29. What does clear() do?

Removes all managed entities.

entityManager.clear();

30. What does refresh() do?

Reloads entity from database.

entityManager.refresh(employee);

Persistence Context


31. What is Persistence Context?

A cache that stores managed entities.

Also called:

First Level Cache

32. Benefits of Persistence Context?

Identity Guarantee

Dirty Checking

Caching

Automatic Synchronization

33. What is Identity Guarantee?

Employee e1 =
        entityManager.find(Employee.class, 1L);

Employee e2 =
        entityManager.find(Employee.class, 1L);

Result:

e1 == e2

Returns:

true

Dirty Checking


34. What is Dirty Checking?

Automatic detection of entity changes.

employee.setSalary(200000);

No save needed.

Hibernate generates UPDATE.


35. When does Dirty Checking occur?

flush()

commit()

36. How does Dirty Checking work?

Hibernate stores:

Snapshot

Compares:

Current State
vs
Snapshot

Relationships


37. What are JPA Relationships?

@OneToOne

@OneToMany

@ManyToOne

@ManyToMany

38. Explain OneToOne

Example:

@OneToOne
private Passport passport;

39. Explain OneToMany

Example:

@OneToMany
private List<Employee> employees;

40. Explain ManyToOne

Example:

@ManyToOne
private Department department;

41. Explain ManyToMany

Example:

@ManyToMany
private List<Role> roles;

42. Difference between mappedBy and JoinColumn?

mappedBy

Inverse side.

JoinColumn

Owning side.


Fetching


43. Difference between LAZY and EAGER?

LAZY

Loads when accessed.

EAGER

Loads immediately.


44. Which fetch type should be default?

LAZY

45. What is N+1 Query Problem?

One query loads parent records.

Additional N queries load children.


46. How do you solve N+1?

JOIN FETCH

@EntityGraph

DTO Projection

JPQL


47. What is JPQL?

Java Persistence Query Language.

Uses:

Entity Names

Field Names

Instead of:

Table Names

Column Names

48. Example JPQL Query

@Query("""
       select e
       from Employee e
       where e.department = :department
       """)

49. Difference between JPQL and SQL?

JPQL SQL
Entity Table
Field Column
Portable DB Specific

50. What is Named Query?

Predefined query.

@NamedQuery(
    name="Employee.findAll",
    query="select e from Employee e"
)

Criteria API


51. What is Criteria API?

Type-safe query building API.

Useful for dynamic queries.


52. Why use Criteria API?

Dynamic Search

Type Safety

Complex Filters

Transactions


53. What is @Transactional?

Defines transactional boundary.

@Transactional
public void saveEmployee() {
}

54. Default Propagation?

Propagation.REQUIRED

55. Difference between REQUIRED and REQUIRES_NEW?

REQUIRED

Join existing transaction.

REQUIRES_NEW

Create new transaction.


56. What causes rollback by default?

RuntimeException

Error

Locking


57. What is Optimistic Locking?

Uses version field.

@Version
private Integer version;

58. What is Pessimistic Locking?

Locks row before update.

@Lock(LockModeType.PESSIMISTIC_WRITE)

59. Difference between Optimistic and Pessimistic Locking?

Optimistic Pessimistic
No DB Lock DB Lock
Version Based Row Lock
Better Throughput More Safety

Caching


60. What is First Level Cache?

Persistence Context.

Always enabled.


61. What is Second Level Cache?

Shared cache across sessions.

Examples:

Ehcache

Hazelcast

Redis

62. Difference between First and Second Level Cache?

First Level Second Level
Session Scope Application Scope
Default Enabled Optional

Spring Data JPA


63. What is JpaRepository?

Repository abstraction.

Provides:

CRUD

Pagination

Sorting

64. Difference between CrudRepository and JpaRepository?

JpaRepository includes:

Pagination

Sorting

Flush Operations

65. What is @Query?

Custom JPQL query.

@Query("select e from Employee e")

66. What is @Modifying?

Used for:

UPDATE

DELETE

Queries.


67. What is @EntityGraph?

Loads associations in single query.

Avoids N+1.


Performance Tuning


68. Biggest JPA Performance Issue?

N+1 Query Problem

69. How do you improve JPA performance?

Pagination

Indexes

Caching

Batch Processing

DTO Projection

JOIN FETCH

70. Why use DTO Projection?

Load only required fields.


71. Why use Pagination?

Avoid loading millions of rows.


72. Why use Batch Processing?

Improve insert/update performance.


Advanced Questions


73. Why should OSIV be disabled?

spring.jpa.open-in-view=false

Prevents unnecessary lazy loading during response rendering.


74. What is the best strategy for large data processing?

Pagination

Batch Processing

Chunk Processing

Spring Batch

75. What would you check if a JPA API is slow?

Checklist:

SQL Count

N+1 Queries

Indexes

Execution Plan

Fetch Strategy

Pagination

Caching

Transaction Scope

Most Frequently Asked JPA Interview Questions

  1. What is JPA?
  2. Difference between JPA and Hibernate?
  3. What is EntityManager?
  4. What is Persistence Context?
  5. Explain Entity Lifecycle.
  6. Difference between persist and merge?
  7. What is Dirty Checking?
  8. Difference between flush and commit?
  9. What is N+1 Query Problem?
  10. Difference between Lazy and Eager Loading?
  11. What is JPQL?
  12. What is @Transactional?
  13. Difference between Optimistic and Pessimistic Locking?
  14. What is First Level Cache?
  15. What is Second Level Cache?
  16. What is JpaRepository?
  17. What is DTO Projection?
  18. What is Batch Processing?
  19. What is @EntityGraph?
  20. How do you optimize JPA performance?

Architect Round Questions

How would you design a search API for 50 million records?

Answer:

Pagination

DTO Projection

Indexes

Read Replica

Caching

EntityGraph

Read-Only Transactions

How would you optimize a slow JPA application?

1. Check N+1

2. Check SQL Count

3. Verify Indexes

4. Add Pagination

5. Use DTO Projection

6. Enable Batch Processing

7. Review Cache Strategy

8. Monitor DB Execution Plans

Summary

For Mid-Level Interviews focus on:

Entity Lifecycle

EntityManager

JPQL

Relationships

Transactions

For Senior/Lead Interviews focus on:

Caching

Performance Tuning

Locking

Batch Processing

Architecture Decisions

Master these 75 JPA interview questions and you will be well prepared for most Spring Boot, JPA, Hibernate, and Architect-level interviews.