JPA

JPA

Top Interview Questions

About JPA

 

Introduction to JPA

Java Persistence API (JPA) is a specification in the Java Enterprise Edition (Java EE) platform that provides a standard framework for object-relational mapping (ORM). ORM allows developers to map Java objects to relational database tables and vice versa. JPA simplifies database operations and abstracts the low-level complexities of JDBC (Java Database Connectivity), making it easier to manage data persistence in Java applications.

Introduced as part of Java EE 5 in 2006, JPA is not an implementation itself but a specification. Implementations such as Hibernate, EclipseLink, OpenJPA, and DataNucleus provide the actual functionality. JPA aims to provide a POJO-based persistence model, meaning entities can be simple Java classes without needing to extend specific base classes.


Why JPA?

Before JPA, Java applications relied heavily on JDBC for database operations. While JDBC is powerful, it has several limitations:

  1. Verbose Code: Every query requires manual handling of SQL statements, result sets, and exception handling.

  2. Database Dependence: SQL queries may be database-specific, reducing portability.

  3. Object-Relational Impedance Mismatch: Mapping Java objects to relational tables manually is error-prone and tedious.

  4. Transaction Management Complexity: Managing transactions manually with JDBC is cumbersome.

JPA addresses these issues by providing:

  • Entity-based persistence: Java classes represent database tables.

  • Database independence: JPQL (Java Persistence Query Language) abstracts the SQL syntax.

  • Automatic mapping: JPA handles the mapping between objects and database tables.

  • Transaction management support: Works seamlessly with Java Transaction API (JTA) and local transactions.


Core Concepts of JPA

  1. Entity:
    An entity is a lightweight, persistent domain object representing a table in a relational database. Each entity instance corresponds to a row in the table.
    Example:

    import jakarta.persistence.Entity;
    import jakarta.persistence.Id;
    
    @Entity
    public class Employee {
        @Id
        private Long id;
        private String name;
        private String department;
    
        // Getters and Setters
    }
    

    Here, the Employee class is an entity, and @Id marks the primary key.

  2. Entity Manager:
    The EntityManager interface is the core of JPA, responsible for managing entity lifecycle, performing CRUD operations, and executing queries.
    Example:

    EntityManagerFactory emf = Persistence.createEntityManagerFactory("myPU");
    EntityManager em = emf.createEntityManager();
    
    em.getTransaction().begin();
    Employee emp = new Employee();
    emp.setId(1L);
    emp.setName("John Doe");
    emp.setDepartment("IT");
    em.persist(emp); // Save entity
    em.getTransaction().commit();
    em.close();
    
  3. Persistence Unit:
    A persistence unit is a logical grouping of entities and configuration metadata, defined in persistence.xml. It includes database connection details and entity classes.
    Example:

    <persistence xmlns="https://jakarta.ee/xml/ns/persistence" version="3.0">
        <persistence-unit name="myPU">
            <class>com.example.Employee</class>
            <properties>
                <property name="jakarta.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/mydb"/>
                <property name="jakarta.persistence.jdbc.user" value="root"/>
                <property name="jakarta.persistence.jdbc.password" value="password"/>
                <property name="jakarta.persistence.jdbc.driver" value="com.mysql.cj.jdbc.Driver"/>
            </properties>
        </persistence-unit>
    </persistence>
    
  4. JPQL (Java Persistence Query Language):
    JPQL is an object-oriented query language similar to SQL but operates on entity objects rather than database tables.
    Example:

    List<Employee> employees = em.createQuery("SELECT e FROM Employee e WHERE e.department = :dept", Employee.class)
                                 .setParameter("dept", "IT")
                                 .getResultList();
    
  5. Entity Relationships:
    JPA supports mapping relationships between entities using annotations:

    • One-to-One (@OneToOne): Each entity instance is associated with exactly one instance of another entity.

    • One-to-Many (@OneToMany): One entity relates to multiple instances of another entity.

    • Many-to-One (@ManyToOne): Many entities relate to a single entity.

    • Many-to-Many (@ManyToMany): Multiple instances of entities relate to multiple instances of another entity.

    Example:

    @OneToMany(mappedBy = "department")
    private List<Employee> employees;
    
  6. Entity Lifecycle:
    JPA defines states for entities:

    • Transient: New instance, not associated with the persistence context.

    • Persistent: Managed by EntityManager and synchronized with the database.

    • Detached: Previously persistent but currently unmanaged.

    • Removed: Scheduled for deletion from the database.

  7. Caching:
    JPA provides first-level (per EntityManager) and second-level (shared across EntityManagerFactory) caching for performance optimization.


Advantages of Using JPA

  1. Productivity: Reduces boilerplate code for database operations.

  2. Portability: Works with multiple relational databases without changing Java code.

  3. Maintainability: Clear separation between business logic and persistence logic.

  4. Performance: Supports caching, batch operations, and lazy loading.

  5. Standardization: Being a Java standard, it allows switching implementations (e.g., Hibernate, EclipseLink) with minimal changes.


Annotations in JPA

JPA provides various annotations to simplify mapping and configuration:

  1. @Entity: Marks a class as a JPA entity.

  2. @Table: Specifies the table name in the database.

  3. @Id: Marks the primary key field.

  4. @GeneratedValue: Defines primary key generation strategy.

  5. @Column: Customizes column mapping.

  6. @Transient: Marks a field to be ignored by persistence.

  7. @Embedded & @Embeddable: Support embedding a value object inside an entity.


Transactions in JPA

JPA supports two types of transactions:

  1. Resource-local transactions: Managed locally using EntityManager.getTransaction().

  2. JTA (Java Transaction API) transactions: Managed by the application server, suitable for distributed transactions.

Example:

em.getTransaction().begin();
em.persist(emp);
em.getTransaction().commit();

Common JPA Features

  1. Criteria API: Type-safe query creation using Java objects instead of string-based JPQL.

  2. Named Queries: Predefined queries stored at the entity or XML level.

  3. Lazy vs Eager Loading: Controls when related entities are loaded.

  4. Cascade Operations: Automatically propagate operations (persist, remove) to related entities.

  5. Optimistic Locking: Prevents lost updates in concurrent transactions using @Version.


JPA Implementations

While JPA is a specification, several popular implementations exist:

  1. Hibernate: Most widely used; supports advanced ORM features.

  2. EclipseLink: Reference implementation of JPA.

  3. OpenJPA: Apache project, compatible with JPA standard.

  4. DataNucleus: Provides support for various datastores including RDBMS and NoSQL.

Fresher Interview Questions

 

1. What is JPA?

Answer:
JPA (Java Persistence API) is a Java specification used to persist, read, update, and delete data from relational databases using Java objects.

  • It provides Object–Relational Mapping (ORM)

  • It is only a specification, not an implementation

  • Implementations include:

    • Hibernate

    • EclipseLink

    • OpenJPA

πŸ‘‰ JPA allows developers to work with Java objects instead of SQL queries.


2. What is ORM (Object Relational Mapping)?

Answer:
ORM is a technique that maps:

  • Java classes → Database tables

  • Java objects → Table rows

  • Java fields → Table columns

Example:

@Entity
class Employee {
   @Id
   private int id;
   private String name;
}

Maps to:

EMPLOYEE (ID, NAME)

ORM reduces boilerplate JDBC code and improves productivity.


3. Difference between JPA and Hibernate?

JPA Hibernate
Specification Implementation
Defined by Java Provided by Red Hat
Standard API Vendor-specific features
Portable Not fully portable

πŸ‘‰ Hibernate implements JPA and also provides extra features.


4. What is an Entity?

Answer:
An Entity is a Java class mapped to a database table.

Rules:

  • Must be annotated with @Entity

  • Must have a primary key (@Id)

  • Must have a default constructor

Example:

@Entity
public class Student {
   @Id
   private int id;
   private String name;
}

5. What is @Id annotation?

Answer:
@Id is used to define the primary key of an entity.

Example:

@Id
private Long empId;

Every entity must have exactly one primary key.


6. What is @GeneratedValue?

Answer:
Used to auto-generate primary key values.

Strategies:

  • AUTO

  • IDENTITY

  • SEQUENCE

  • TABLE

Example:

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;

7. What is Persistence?

Answer:
Persistence means storing Java object data permanently in a database and retrieving it later.

JPA handles persistence automatically using ORM.


8. What is EntityManager?

Answer:
EntityManager is the main interface used to interact with the database.

Functions:

  • Persist entity

  • Find entity

  • Remove entity

  • Update entity

Example:

entityManager.persist(employee);

9. What is persistence.xml?

Answer:
It is a configuration file that:

  • Defines database connection

  • Specifies JPA provider

  • Declares persistence unit

Location:

META-INF/persistence.xml

10. What is Persistence Unit?

Answer:
A persistence unit defines:

  • Database connection

  • Entity classes

  • JPA provider

Example:

<persistence-unit name="myPU">

11. What are JPA Annotations?

Answer:
Annotations define how Java classes map to database tables.

Common annotations:

  • @Entity

  • @Table

  • @Id

  • @Column

  • @Transient

  • @OneToOne

  • @OneToMany

  • @ManyToOne


12. What is @Table annotation?

Answer:
Used to specify the table name.

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

13. What is @Column annotation?

Answer:
Maps a Java field to a table column.

@Column(name="EMP_NAME", nullable=false)
private String name;

14. What is @Transient?

Answer:
Fields marked with @Transient are not persisted to the database.

@Transient
private int tempValue;

15. What is Entity Lifecycle?

Answer:
An entity goes through these states:

  1. New – Not associated with DB

  2. Managed – Associated with persistence context

  3. Detached – No longer managed

  4. Removed – Marked for deletion


16. What is Persistence Context?

Answer:
A persistence context is a cache that stores managed entities.

  • Maintains entity uniqueness

  • Automatically synchronizes changes with DB


17. What is JPQL?

Answer:
JPQL (Java Persistence Query Language) is:

  • Object-oriented query language

  • Works on entity objects, not tables

Example:

SELECT e FROM Employee e WHERE e.salary > 50000

18. Difference between JPQL and SQL?

JPQL SQL
Uses entity names Uses table names
Object-oriented Database-oriented
Portable DB-specific

19. What is find() method?

Answer:
Used to retrieve an entity by primary key.

Employee e = entityManager.find(Employee.class, 1);

20. What is persist()?

Answer:
Stores a new entity into the database.

entityManager.persist(employee);

21. What is merge()?

Answer:
Used to update detached entities.

entityManager.merge(employee);

22. What is remove()?

Answer:
Deletes an entity from the database.

entityManager.remove(employee);

23. What are Relationships in JPA?

Answer:
JPA supports relationships between entities:

  • @OneToOne

  • @OneToMany

  • @ManyToOne

  • @ManyToMany


24. What is @ManyToOne?

Answer:
Many entities are related to one entity.

Example:

@ManyToOne
@JoinColumn(name="dept_id")
private Department department;

25. What is @OneToMany?

Answer:
One entity is related to many entities.

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

26. What is Fetch Type?

Answer:
Defines when data is loaded.

  • EAGER – Load immediately

  • LAZY – Load when required

@OneToMany(fetch = FetchType.LAZY)

27. What is Cascade Type?

Answer:
Defines how operations propagate.

Common types:

  • PERSIST

  • MERGE

  • REMOVE

  • ALL

@OneToMany(cascade = CascadeType.ALL)

28. What is @JoinColumn?

Answer:
Defines the foreign key column.

@JoinColumn(name="dept_id")

29. What is Primary Key?

Answer:
A primary key uniquely identifies each row in a table.

In JPA, it is defined using @Id.


30. Advantages of JPA

Answer:

  • Reduces boilerplate JDBC code

  • Database independent

  • Easy CRUD operations

  • Object-oriented approach

  • Integrates well with Spring


31. What is @MappedSuperclass?

Answer:
@MappedSuperclass is used when you want common fields to be shared across multiple entities.

  • No table is created for it

  • Fields are mapped to child entity tables

@MappedSuperclass
public class BaseEntity {
   @Id
   private Long id;
   private LocalDateTime createdDate;
}

32. Difference between @Entity and @MappedSuperclass?

@Entity @MappedSuperclass
Table is created No table created
Can be queried Cannot be queried
Independent entity Only base class

33. What is @Embeddable?

Answer:
Used to represent a value object whose fields are embedded into an entity.

@Embeddable
class Address {
   private String city;
   private String pincode;
}

34. What is @Embedded?

Answer:
Used to embed an @Embeddable class into an entity.

@Embedded
private Address address;

35. Difference between @Embedded and @OneToOne?

@Embedded @OneToOne
Same table Separate table
No identity Has identity
Value object Entity

36. What is @Enumerated?

Answer:
Used to persist Java enums.

@Enumerated(EnumType.STRING)
private Status status;

Types:

  • ORDINAL (stores index – risky)

  • STRING (stores name – recommended)


37. What is @Temporal?

Answer:
Maps Java Date to DB types.

@Temporal(TemporalType.DATE)
private Date dob;

38. What is @NamedQuery?

Answer:
Predefined JPQL queries defined at entity level.

@NamedQuery(
  name="Employee.findAll",
  query="SELECT e FROM Employee e"
)

Advantages:

  • Better performance

  • Centralized queries


39. What is Native Query?

Answer:
SQL queries written directly.

entityManager
  .createNativeQuery("SELECT * FROM EMP")
  .getResultList();

Used when JPQL is insufficient.


40. Difference between JPQL and Native Query?

JPQL Native
Portable DB specific
Uses entities Uses tables
Safer Faster sometimes

41. What is Lazy Loading?

Answer:
Data is loaded only when accessed.

@OneToMany(fetch = FetchType.LAZY)

Improves performance.


42. What is Eager Loading?

Answer:
Data is loaded immediately with the entity.

@ManyToOne(fetch = FetchType.EAGER)

Can impact performance if overused.


43. What is the N+1 Select Problem?

Answer:
Occurs when:

  • One query loads parent

  • Multiple queries load child entities

Solution:

  • JOIN FETCH

  • Entity Graphs


44. What is JOIN FETCH?

Answer:
Fetches related entities in a single query.

SELECT e FROM Employee e JOIN FETCH e.department

45. What is Entity Graph?

Answer:
Defines fetch plans dynamically.

@EntityGraph(attributePaths = {"department"})

Avoids N+1 issue.


46. What is Optimistic Locking?

Answer:
Uses versioning to handle concurrent updates.

@Version
private int version;

Fails update if data is modified by another user.


47. What is Pessimistic Locking?

Answer:
Locks DB rows to prevent others from updating.

LockModeType.PESSIMISTIC_WRITE

48. Difference between Optimistic and Pessimistic Locking?

Optimistic Pessimistic
No DB lock DB lock
Better performance Slower
Uses version Uses locks

49. What is @Version?

Answer:
Used for optimistic locking.

@Version
private Long version;

50. What is Dirty Checking?

Answer:
JPA automatically detects entity changes and updates DB without explicit update query.


51. What is Flush?

Answer:
Flush synchronizes persistence context with database.

entityManager.flush();

52. Difference between Flush and Commit?

Flush Commit
Syncs data Saves transaction
Does not end transaction Ends transaction

53. What is detach()?

Answer:
Removes entity from persistence context.

entityManager.detach(entity);

54. What is clear()?

Answer:
Clears entire persistence context.

entityManager.clear();

55. What is refresh()?

Answer:
Reloads entity state from database.

entityManager.refresh(entity);

56. What is @OrderBy?

Answer:
Orders collection results.

@OrderBy("name ASC")

57. What is @OrderColumn?

Answer:
Maintains list order using index column.


58. What is @SecondaryTable?

Answer:
Maps entity to multiple tables.

@SecondaryTable(name="EMP_DETAILS")

59. What is @Inheritance?

Answer:
Used for entity inheritance.

Strategies:

  • SINGLE_TABLE

  • JOINED

  • TABLE_PER_CLASS


60. Difference between Inheritance Strategies?

Strategy Tables Performance
SINGLE_TABLE One Fast
JOINED Multiple Slower
TABLE_PER_CLASS Many Medium

61. What is @DiscriminatorColumn?

Answer:
Identifies subclass type in inheritance.


62. What is @SQLDelete?

Answer:
Used for soft delete.

@SQLDelete(sql="UPDATE emp SET deleted=true WHERE id=?")

63. What is Soft Delete?

Answer:
Marks record as deleted without removing it physically.


64. What is @Where?

Answer:
Filters entity results.

@Where(clause="deleted=false")

65. What are JPA Callbacks?

Answer:
Lifecycle methods:

  • @PrePersist

  • @PostPersist

  • @PreUpdate

  • @PostRemove


66. What is @PrePersist?

Answer:
Executed before entity is saved.

@PrePersist
void beforeSave(){}

67. What is @PostLoad?

Answer:
Executed after entity is loaded.


68. What is @Basic?

Answer:
Default mapping for simple fields.


69. What is @Access?

Answer:
Defines access type:

  • FIELD

  • PROPERTY


70. Advantages of JPA in Real Projects

Answer:

  • Clean architecture

  • Reduced SQL dependency

  • Easy maintenance

  • Scalable enterprise applications

 

Experienced Interview Questions

 

1. What is JPA and why is it used?

JPA (Java Persistence API) is a Java specification that provides a standard way to map Java objects to relational database tables and manage relational data in Java applications.

Why JPA?

  • Eliminates boilerplate JDBC code

  • Provides ORM (Object Relational Mapping)

  • Vendor-independent (Hibernate, EclipseLink, OpenJPA)

  • Integrates easily with Spring and Spring Boot

  • Supports caching, transactions, and relationships

JPA itself is not an implementation, it is only a specification.


2. Difference between JPA and Hibernate

JPA Hibernate
Specification Implementation
Part of Java EE/Jakarta EE Third-party framework
Defines annotations & APIs Provides actual ORM behavior
Vendor-neutral Hibernate-specific features

πŸ‘‰ Hibernate implements JPA, but also offers extra features like:

  • Second-level cache

  • Hibernate Criteria API

  • Interceptors


3. What is an Entity?

An Entity is a persistent Java class mapped to a database table.

Characteristics:

  • Annotated with @Entity

  • Must have a primary key

  • Must have a default constructor

  • Serializable (recommended)

@Entity
@Table(name = "employee")
public class Employee {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String name;
}

4. What is the role of @Id and @GeneratedValue?

  • @Id → Marks the primary key

  • @GeneratedValue → Specifies how the primary key is generated

Generation Strategies:

  • AUTO

  • IDENTITY

  • SEQUENCE

  • TABLE

@GeneratedValue(strategy = GenerationType.SEQUENCE)

5. What is Persistence Context?

A Persistence Context is a set of managed entity instances.

Key points:

  • Managed by EntityManager

  • Ensures one object per database row

  • Tracks entity changes automatically

Entity States:

  1. Transient – New object, not associated

  2. Managed – Attached to persistence context

  3. Detached – Exists but not managed

  4. Removed – Marked for deletion


6. Difference between persist() and merge()

persist() merge()
Used for new entities Used for detached entities
Throws exception if entity exists Updates existing entity
Returns void Returns managed entity
entityManager.persist(emp);
entityManager.merge(emp);

7. What is EntityManager?

EntityManager is the core JPA interface for interacting with persistence context.

Responsibilities:

  • CRUD operations

  • Query execution

  • Transaction management

Common methods:

  • persist()

  • find()

  • remove()

  • merge()

  • createQuery()


8. What is @Transactional in JPA?

@Transactional defines transaction boundaries.

Benefits:

  • Automatic commit/rollback

  • Cleaner code

  • Handles runtime exceptions

@Transactional
public void saveEmployee(Employee emp) {
    entityManager.persist(emp);
}

9. Difference between find() and getReference()

find() getReference()
Immediately hits DB Returns proxy
Returns actual entity Lazy-loaded
Null if not found Exception on access

10. What is JPQL?

JPQL (Java Persistence Query Language) is object-oriented query language.

Example:

SELECT e FROM Employee e WHERE e.salary > 50000

πŸ‘‰ Uses entity names and fields, not table/column names.


11. Difference between JPQL and Native Query

JPQL Native Query
Database independent DB specific
Uses entity fields Uses table columns
Slower for complex queries Faster, optimized
@Query(value = "SELECT * FROM employee", nativeQuery = true)

12. What is Lazy and Eager Fetching?

  • LAZY → Data loaded when accessed

  • EAGER → Data loaded immediately

@OneToMany(fetch = FetchType.LAZY)

Best Practice:

  • Use LAZY by default

  • Avoid N+1 query issue


13. What is the N+1 Select Problem?

Occurs when:

  • One query loads parent entities

  • N queries load child entities

Solution:

  • JOIN FETCH

  • Entity Graphs

  • Batch fetching

SELECT e FROM Employee e JOIN FETCH e.projects

14. JPA Relationships

Types:

  • @OneToOne

  • @OneToMany

  • @ManyToOne

  • @ManyToMany

Example:

@ManyToOne
@JoinColumn(name = "dept_id")
private Department department;

15. Difference between mappedBy and @JoinColumn

  • mappedBy → Inverse side (no column created)

  • @JoinColumn → Owning side (creates FK)


16. What is Cascade Type?

Cascade propagates operations from parent to child.

Types:

  • PERSIST

  • MERGE

  • REMOVE

  • REFRESH

  • DETACH

  • ALL

@OneToMany(cascade = CascadeType.ALL)

17. What is Orphan Removal?

Deletes child entity when removed from parent collection.

@OneToMany(orphanRemoval = true)

18. First-Level Cache vs Second-Level Cache

First Level Cache Second Level Cache
Default Optional
EntityManager scoped SessionFactory scoped
Always enabled Requires config

19. Optimistic vs Pessimistic Locking

Optimistic Locking

  • Uses @Version

  • No DB lock

  • Best for low contention

@Version
private int version;

Pessimistic Locking

  • DB-level lock

  • Used in high contention


20. What is Dirty Checking?

JPA automatically detects entity changes and updates DB without explicit update query.


21. Difference between save() and saveAndFlush()

  • save() → Persist later

  • saveAndFlush() → Immediately flush to DB


22. What is Flush in JPA?

Flush synchronizes persistence context with database.

entityManager.flush();

23. What is @Embeddable and @Embedded?

Used for value objects.

@Embeddable
class Address {}

@Embedded
private Address address;

24. What is Entity Graph?

Defines fetch plan dynamically to avoid N+1 issues.


25. Real-Time Scenario Question

How do you improve JPA performance in production?

Answer:

  • Use LAZY loading

  • Avoid unnecessary joins

  • Use pagination

  • Enable second-level cache

  • Use batch processing

  • Optimize queries

  • Avoid bi-directional relationships when not needed


26. Difference between JPA Repository and CrudRepository

  • CrudRepository → Basic CRUD

  • JpaRepository → Pagination, sorting, flush


27. What is Specification in JPA?

Used for dynamic queries using Criteria API.


28. When do you use Native Queries?

  • Complex joins

  • DB-specific functions

  • Performance-critical queries


29. What happens if @Transactional is missing?

  • Partial updates

  • No rollback

  • Lazy loading exceptions


30. Common JPA Exceptions

  • LazyInitializationException

  • EntityNotFoundException

  • OptimisticLockException

  • TransactionRequiredException


31. How JPA handles concurrency?

  • Optimistic locking

  • Pessimistic locking

  • Versioning


32. Difference between @Column(insertable=false, updatable=false)

Used for read-only fields.


33. How do you handle pagination?

PageRequest.of(0, 10);

34. Difference between @OrderBy and @OrderColumn

  • @OrderBy → Sorting

  • @OrderColumn → Maintains index


35. Best Practices for 4+ Years Experience

  • Prefer DTO projections

  • Avoid EAGER fetching

  • Use proper indexes

  • Handle transactions properly

  • Monitor SQL logs

  • Understand entity lifecycle


36. What is the difference between EntityManager and EntityManagerFactory?

EntityManager EntityManagerFactory
Manages persistence context Creates EntityManager instances
Lightweight Heavyweight
Not thread-safe Thread-safe
Per transaction/request One per application

37. Why is EntityManager not thread-safe?

Because it maintains:

  • Persistence context

  • Transaction state

  • Managed entity instances

Sharing it across threads can cause data inconsistency.


38. What is @Version and how does it work internally?

@Version enables optimistic locking.

How it works:

  1. Entity loaded with version = 1

  2. Update request checks version

  3. If version mismatches → exception

@Version
private Long version;

Prevents lost updates without database locks.


39. Difference between Optimistic and Pessimistic Locking (Real Scenario)

Optimistic Locking:

  • Banking account profile update

  • Product catalog

Pessimistic Locking:

  • Ticket booking

  • Inventory reservation

@Lock(LockModeType.PESSIMISTIC_WRITE)

40. What is LazyInitializationException and how do you fix it?

Occurs when:

  • Lazy collection accessed outside transaction

Fixes:

  • Use JOIN FETCH

  • Open Session in View (not recommended)

  • DTO projection

  • Transactional service layer


41. What is DTO Projection and why is it important?

DTO projection fetches only required columns.

Example:

SELECT new com.dto.EmployeeDTO(e.id, e.name)
FROM Employee e

Benefits:

  • Faster queries

  • Less memory usage

  • Better performance


42. Difference between JOIN, FETCH JOIN, and LEFT JOIN

JOIN FETCH JOIN
Filters data Fetches associations
Does not initialize collections Initializes relations
Used in conditions Avoids N+1 problem

43. What is Criteria API and when to use it?

Criteria API builds type-safe dynamic queries.

Used when:

  • Search screens

  • Dynamic filters

  • Complex conditions


44. What is @NamedQuery vs @Query?

@NamedQuery @Query
Defined at entity level Defined at repository
Precompiled Runtime parsed
Better performance More flexible

45. What is flush() vs commit()?

  • flush() → Syncs changes to DB

  • commit() → Finalizes transaction

Flush can happen multiple times before commit.


46. What is clear() in EntityManager?

Removes all managed entities from persistence context.

entityManager.clear();

Used in batch processing.


47. What is Batch Processing in JPA?

Processing large data in chunks.

Best Practices:

  • Use flush() and clear()

  • Disable second-level cache

  • Use batch size

hibernate.jdbc.batch_size=50

48. Difference between remove() and deleteById()

  • remove() → Works on managed entity

  • deleteById() → Direct delete query


49. What is Soft Delete and how do you implement it?

Instead of deleting records, mark them inactive.

@Where(clause = "is_deleted = false")

50. What is @DynamicUpdate?

Updates only modified columns.

Benefit:

  • Reduces DB load

  • Improves performance


51. What is Second Level Cache and when should you use it?

Caches entities across sessions.

Use when:

  • Read-heavy applications

  • Rare updates

Do NOT use for frequently changing data.


52. Difference between @Where and @Filter

@Where @Filter
Static condition Dynamic condition
Always applied Applied at runtime

53. How does JPA handle inheritance?

Strategies:

  • SINGLE_TABLE

  • JOINED

  • TABLE_PER_CLASS

Best practice: JOINED


54. What is @MappedSuperclass?

Used for common fields like:

  • createdDate

  • updatedDate

No table created.


55. What is the difference between @Transient and transient?

@Transient transient
JPA annotation Java keyword
ORM ignored Serialization ignored

56. What is @ElementCollection?

Used for value types without entity identity.

@ElementCollection
List<String> skills;

57. What is the difference between equals() and hashCode() in JPA entities?

Should be based on:

  • Business key

  • Not auto-generated ID

Prevents issues in collections.


58. What are Entity Listeners?

Callbacks for entity lifecycle events.

@PrePersist
@PreUpdate

59. What is @SQLDelete?

Custom delete query (used for soft delete).


60. What is JPA Auditing?

Automatically tracks:

  • CreatedBy

  • CreatedDate

  • ModifiedBy

  • ModifiedDate


61. How do you handle multi-tenancy in JPA?

  • Schema based

  • Database based

  • Discriminator based


62. Difference between @OrderBy and database ORDER BY

  • @OrderBy → ORM-level sorting

  • SQL ORDER BY → DB-level sorting


63. How do you debug slow JPA queries?

  • Enable SQL logs

  • Analyze execution plan

  • Check indexes

  • Monitor N+1

  • Use query hints


64. What is @QueryHint?

Provides optimization hints.


65. When should you avoid JPA?

  • Bulk operations

  • Complex reporting

  • Highly DB-specific logic

Use JDBC / Native SQL instead.


66. Real-Time Scenario Question

How do you fix performance issues caused by bi-directional relationships?

Answer:

  • Make relationship uni-directional

  • Use DTO projections

  • Avoid EAGER fetching

  • Limit serialization (JSON infinite loop)


67. What is @JsonIgnore used for with JPA?

Prevents infinite recursion during JSON serialization.


68. Difference between save() and persist()?

  • save() → Spring Data JPA

  • persist() → JPA EntityManager


69. What is @Immutable?

Marks entity as read-only.


70. What happens during application startup in JPA?

  • Entity scanning

  • Mapping validation

  • Schema generation (ddl-auto)


71. How do you handle schema migration?

Use:

  • Flyway

  • Liquibase

Never rely on ddl-auto in production.


72. Explain JPA lifecycle events order

  1. @PrePersist

  2. @PostPersist

  3. @PreUpdate

  4. @PostUpdate

  5. @PreRemove

  6. @PostRemove


73. Difference between findAll() and pagination?

  • findAll() loads everything

  • Pagination loads limited data


74. What is the impact of FetchType.EAGER in production?

  • Performance issues

  • Unnecessary joins

  • Memory overhead

Avoid it.


75. How do you design a scalable JPA application?

  • DTO projections

  • Lazy loading

  • Proper indexing

  • Batch processing

  • Caching strategy

  • Monitoring