Spring Data JPA interview questions are mainly asked to test your understanding of database operations using JPA + Hibernate in Spring Boot. These questions focus on entities, repositories, query methods, JPQL, pagination, sorting, transactions, relationships, and performance best practices.
1. What is Spring Data JPA?
Spring Data JPA is a Spring framework module that simplifies database operations by providing ready-made repository interfaces for performing CRUD operations without writing SQL queries. It works on top of JPA (Java Persistence API) and internally uses Hibernate as the default ORM provider.
- Provides JpaRepository for CRUD + pagination + sorting
- Reduces boilerplate code by generating queries automatically
- Supports JPQL and custom queries using @Query

2. What is the difference between JPA and Hibernate?
JPA and Hibernate are both used for ORM (Object Relational Mapping) in Java, but the main difference is that JPA is a specification, while Hibernate is a framework (implementation) that provides the actual working code.

| Feature | JPA | Hibernate |
|---|---|---|
| Type | Specification (Rules) | ORM Framework (Implementation) |
| Provided by | Java / Jakarta EE | Red Hat Community |
| Purpose | Defines ORM standards | Implements JPA + extra features |
| Dependency | Needs implementation | Works directly as ORM tool |
| Extra Features | Limited | Caching, HQL, extra annotations |
3. What is an Entity in Spring Data JPA?
An Entity in Spring Data JPA is a Java class that represents a table in the database. Each object of the entity class represents one row (record), and its fields represent the table columns.
- Marked using @Entity annotation
- Must have a primary key using @Id
- Used by Hibernate/JPA to perform CRUD operations automatically
4. What is the use of @Id in JPA?
@Id is a JPA annotation used to define the primary key of an entity class. It tells JPA/Hibernate which field uniquely identifies each record (row) in the database table.
- Marks a field as unique identifier for the entity
- Required for every entity class in JPA
- Works with @GeneratedValue for auto-increment primary keys
5. What is @GeneratedValue in Spring Data JPA?
@GeneratedValue is a JPA annotation used to automatically generate values for the primary key field. It helps in auto-incrementing the @Id column without manually assigning values.
- Used with @Id for automatic primary key generation
- Supports strategies like AUTO, IDENTITY, SEQUENCE, TABLE
- Prevents manual errors while inserting new records
6. What is Repository in Spring Data JPA?
A Repository in Spring Data JPA is an interface that provides built-in methods to perform database operations like save, update, delete, and fetch records. It removes the need to write DAO classes and SQL queries for common CRUD tasks.
- Created by extending JpaRepository or CrudRepository
- Provides ready-made methods like save(), findById(), findAll()
- Supports custom queries using method names or @Query
Example:
import org.springframework.data.jpa.repository.JpaRepository;
public interface StudentRepository extends JpaRepository<Student, Long> {
}
7. What is JpaRepository?
JpaRepository is a Spring Data JPA interface that provides complete database operations like CRUD, pagination, and sorting. It is mainly used to avoid writing DAO classes and common SQL queries.
- Extends CrudRepository and PagingAndSortingRepository
- Provides methods like save(), findAll(), deleteById()
- Supports pagination and sorting using Pageable and Sort
8. What is the difference between CrudRepository and JpaRepository?
CrudRepository and JpaRepository both are used to perform database operations in Spring Data JPA. The main difference is that CrudRepository provides only basic CRUD methods, while JpaRepository provides extra features like pagination, sorting, and batch operations.
| Feature | CrudRepository | JpaRepository |
|---|---|---|
| CRUD Support | Basic CRUD only | CRUD + many extra features |
| Pagination | Not available | Available (Pageable) |
| Sorting | Not available | Available (Sort) |
| Batch Operations | Not available | Available (saveAll(), etc.) |
| Flush | Not available | Available (flush()) |
| Best Use | Small/simple apps | Large/real projects |
9. What is the use of save() method?
The save() method in Spring Data JPA is used to store an entity in the database. It can perform both insert and update depending on whether the entity already has an ID value.
- Inserts a new record if the entity ID is not present
- Updates an existing record if the entity ID already exists
- Returns the saved entity object with updated values
10. What is findById() in Spring Data JPA?
The findById() method in Spring Data JPA is used to retrieve an entity from the database using its primary key. It returns an Optional containing the entity if found, or empty if not.
- Fetches a single record by its ID
- Returns Optional<Entity> to handle null safely
- Commonly used to read data before update or delete operations
11. What are derived query methods?
Derived query methods in Spring Data JPA are methods in a repository interface whose names define the query automatically. Spring parses the method name and generates the corresponding SQL or JPQL behind the scenes.
- No need to write @Query manually for simple queries
- Follows naming conventions like findBy, countBy, deleteBy
- Example: findByName(String name) automatically fetches records with matching name
12. What is @Query annotation?
The @Query annotation in Spring Data JPA is used to define custom JPQL or SQL queries directly on repository methods. It is helpful when derived query methods are not sufficient for complex queries.
- Can write JPQL or native SQL queries using nativeQuery = true
- Used for complex filtering, joins, or aggregations
Example:
@Query("SELECT s FROM Student s WHERE s.name = :name")
List<Student> findByStudentName(@Param("name") String name);
13. What is the difference between JPQL and SQL?
JPQL and SQL are both used to query databases, but the main difference is that JPQL works with entity objects, while SQL works directly with database tables. JPQL is object-oriented and database-independent.
| Feature | JPQL | SQL |
|---|---|---|
| Query Target | Works with Java entities | Works with database tables |
| Syntax | Object-oriented | Table/column-based |
| Database Dependency | Database-independent | Database-specific |
| Joins | Uses entity relationships | Uses table relationships |
| Return Type | Returns entity objects | Returns raw table rows |
14. What is nativeQuery in Spring Data JPA?
In Spring Data JPA, nativeQuery is used with the @Query annotation to execute plain SQL queries directly on the database instead of using JPQL. It is helpful when JPQL cannot handle complex database-specific queries.
- Set nativeQuery = true in @Query
- Allows use of database-specific SQL features
Example:
@Query(value = "SELECT * FROM student WHERE name = :name", nativeQuery = true)
List<Student> findByNameNative(@Param("name") String name);
15. What is pagination in Spring Data JPA?
Pagination in Spring Data JPA is a technique to fetch a subset of records from the database instead of retrieving all at once. It helps improve performance and manage large datasets efficiently.
- Uses Pageable interface to specify page number and size
- Returns a Page<T> object containing content, total pages, and total elements
- Commonly used with findAll(Pageable pageable) for paginated results
16. What is sorting in Spring Data JPA?
Sorting in Spring Data JPA is used to arrange query results in a specific order based on one or more fields. It can be combined with pagination to get ordered subsets of data.
- Uses Sort class to define ascending or descending order
- Can sort by single or multiple fields
Example:
findAll(Sort.by(Sort.Direction.ASC, "name"))
17. What is @Transactional in Spring Data JPA?
@Transactional in Spring Data JPA is an annotation used to manage database transactions automatically. It ensures that all operations within a method are executed in a single transaction, and can be rolled back if an exception occurs.
- Ensures atomicity of database operations
- Can be applied at method or class level
- Supports rollback on exceptions automatically
18. What is Lazy and Eager loading?
Lazy and Eager loading are strategies in JPA to fetch related data from the database. They control when associated entities are loaded to optimize performance.
- Lazy Loading: Related data is loaded only when accessed, saving memory and queries
- Eager Loading: Related data is loaded immediately with the main entity
- Configured using @OneToMany(fetch = FetchType.LAZY) or FetchType.EAGER
19. What is the N+1 problem in JPA?
The N+1 problem in JPA occurs when loading a collection of entities causes an extra query for each associated entity, leading to performance issues. It happens mostly with lazy loading in relationships.
- Fetching a list of N entities triggers 1 query for main entity + N queries for related entities
- Can cause slow performance for large datasets
- Solved using JOIN FETCH in JPQL or @EntityGraph for eager fetching
20. What is the difference between save() and saveAndFlush()?
In Spring Data JPA, both save() and saveAndFlush() are used to persist entities, but the main difference is when changes are written to the database.
| Feature | save() | saveAndFlush() |
|---|---|---|
| Database Write | May delay until transaction commit | Immediately writes to database |
| Return | Saved entity | Saved entity |
| Use Case | Batch inserts/updates | Immediate persistence needed |
| Performance | Faster for multiple operations | Slightly slower due to immediate flush |