Top 10 Spring Data JPA Interview Questions &
Answers
Q: What is Spring Data JPA and why is it used?
A: Spring Data JPA is a part of Spring Data that simplifies data access using JPA (Java Persistence
API). It reduces boilerplate code by providing repositories with CRUD operations, pagination, and
query methods.
Q: Difference between JPA, Hibernate, and Spring Data JPA?
A: - JPA → Specification for ORM.
- Hibernate → Implementation of JPA.
- Spring Data JPA → Abstraction on top of JPA & Hibernate, providing repository support and
reducing boilerplate.
Q: What are JPA repositories in Spring Data JPA?
A: JPA repositories are interfaces provided by Spring Data that extend CrudRepository or
JpaRepository. They automatically provide CRUD, pagination, and sorting without writing
implementation.
Q: What is the difference between CrudRepository and JpaRepository?
A: - CrudRepository → Basic CRUD operations.
- JpaRepository → Adds JPA-specific methods like batch flush, pagination, sorting.
Q: How to define custom queries in Spring Data JPA?
A: - Method Naming Convention → findByName, findByEmail.
- @Query Annotation → Define JPQL/SQL queries.
- Native Query → Using nativeQuery = true.
Q: What is the difference between JPQL and Native SQL in Spring Data JPA?
A: - JPQL → Works on entity objects (portable across databases).
- Native SQL → Works on database tables directly (DB specific).
Q: What is the use of @Entity, @Table, @Id, and @GeneratedValue in JPA?
A: - @Entity → Marks class as JPA entity.
- @Table → Maps entity to DB table.
- @Id → Primary key field.
- @GeneratedValue → Strategy for key generation.
Q: What is the difference between [Link] and [Link]?
A: - EAGER → Loads related entities immediately with the main entity.
- LAZY → Loads related entities only when accessed (better performance).
Q: What is the N+1 select problem in JPA?
A: It occurs when fetching a collection of entities and their relationships cause multiple queries (1
main + N sub-queries). Can be solved using @EntityGraph or JOIN FETCH.
Q: How does pagination work in Spring Data JPA?
A: Spring Data JPA provides Pageable and Page interfaces. Using findAll(Pageable pageable) you
can fetch records page by page with sorting.