Spring Boot Interview Questions and Answers – Part 3 | Spring Data JPA & Hibernate
Introduction :
Welcome to Part 3 of the Spring Boot Interview Questions and Answers series!
In Part 2, we covered Spring Beans, stereotype annotations, REST controllers, request mapping, bean scopes, Spring Profiles, configuration properties, and application configuration files.
In this article, we'll focus on Spring Data JPA and Hibernate, two of the most important topics in Spring Boot interviews. You'll learn about repositories, entity relationships, fetch strategies, transactions, cascading, and performance optimization through commonly asked interview questions.
Let's get started!
21. What is Spring Data JPA?
Answer
Spring Data JPA is a Spring module that simplifies database operations by reducing boilerplate code. It provides ready-made repository interfaces for performing CRUD operations without writing SQL queries manually.
Advantages
Reduces boilerplate code
Supports automatic query generation
Easy pagination and sorting
Integrates seamlessly with Hibernate
22. What is Hibernate? How is it different from JPA?
Answer
JPA (Java Persistence API) is a specification that defines how Java objects should be mapped to relational databases.
Hibernate is one of the most popular implementations of the JPA specification.
| JPA | Hibernate |
|---|---|
| Specification | Implementation |
| Defines standards | Provides actual implementation |
| Cannot work independently | Can work with or without JPA |
23. What is the difference between CrudRepository, PagingAndSortingRepository, and JpaRepository?
CrudRepository
Provides basic CRUD operations.
Example methods:
save()
findById()
delete()
findAll()
PagingAndSortingRepository
Extends CrudRepository and provides pagination and sorting support.
Additional methods include:
findAll(Pageable pageable)
findAll(Sort sort)
JpaRepository
Extends PagingAndSortingRepository and provides additional JPA-specific functionality.
Additional features:
Batch operations
flush()
saveAndFlush()
24. What is the purpose of the @Entity annotation?
Answer
The @Entity annotation tells Hibernate that the class represents a database table.
Example:
@Entity
public class Employee {
@Id
private Long id;
private String name;
}
Each object of the entity corresponds to a row in the database table.
25. What is the difference between save() and saveAndFlush()?
save()
Saves the entity.
Changes are synchronized with the database during transaction commit.
saveAndFlush()
Saves the entity.
Immediately flushes changes to the database.
Use saveAndFlush() when you need the database to reflect changes before the transaction completes.
26. Explain the Entity Lifecycle in JPA.
JPA entities go through different lifecycle states.
Transient
The object is created but is not associated with the persistence context.
Persistent
The entity is managed by Hibernate.
Detached
The entity was managed previously but is no longer associated with the persistence context.
Removed
The entity is marked for deletion and will be removed from the database.
27. What are the different types of entity relationships in JPA?
JPA supports four relationship types:
One-to-One (
@OneToOne)One-to-Many (
@OneToMany)Many-to-One (
@ManyToOne)Many-to-Many (
@ManyToMany)
These annotations define how entities are associated with each other.
28. What is the difference between FetchType.LAZY and FetchType.EAGER?
LAZY Fetching
Data is loaded only when it is accessed.
Advantages
Better performance
Reduced memory usage
EAGER Fetching
Associated data is loaded immediately along with the parent entity.
Interview Tip
Use LAZY loading by default unless immediate loading is required.
29. What is the mappedBy attribute used for?
Answer
The mappedBy attribute specifies the inverse side of a bidirectional relationship.
It prevents Hibernate from creating duplicate foreign keys and identifies which entity owns the relationship.
30. What is Cascading in JPA?
Answer
Cascading allows operations performed on a parent entity to automatically apply to its child entities.
Common cascade types include:
PERSIST
MERGE
REMOVE
REFRESH
DETACH
ALL
Example:
@OneToMany(cascade = CascadeType.ALL)
private List<Employee> employees;
31. What is orphanRemoval?
Answer
When orphanRemoval = true is enabled, removing a child entity from its parent collection automatically deletes it from the database.
This helps maintain data consistency without explicitly deleting child records.
32. What is the @Transactional annotation?
Answer
The @Transactional annotation manages database transactions automatically.
If all operations succeed, the transaction is committed.
If an exception occurs, the transaction is rolled back.
Benefits
Automatic transaction management
Data consistency
Reduced boilerplate code
33. What is the difference between findById() and getReferenceById()?
findById()
Immediately retrieves data from the database.
Returns an
Optional.
getReferenceById()
Returns a proxy object.
Data is fetched only when required.
Useful for lazy loading scenarios.
34. What is the N+1 Query Problem?
Answer
The N+1 Query Problem occurs when one query retrieves parent records and additional queries are executed for each associated child record.
Example:
One query retrieves all departments.
Separate queries retrieve employees for each department.
This increases database calls and negatively impacts performance.
Solutions
Use
JOIN FETCHUse
@EntityGraphOptimize fetch strategies
35. How can you improve JPA performance?
Some common optimization techniques include:
Prefer LAZY fetching over EAGER.
Retrieve only required columns.
Use pagination for large datasets.
Avoid unnecessary database calls.
Use appropriate indexes.
Optimize queries using JOIN FETCH where needed.
Monitor SQL queries during development.
Conclusion :
In Part 3, we explored the most frequently asked Spring Data JPA and Hibernate interview questions, including repositories, entity relationships, fetch strategies, transactions, cascading, and performance optimization. These concepts are fundamental for developing efficient database-driven Spring Boot applications and are commonly discussed in technical interviews.
In Part 4, we'll cover Spring Security, JWT Authentication, Exception Handling, Validation, Logging, and Spring Boot Actuator—topics that are frequently asked in advanced Spring Boot interviews and widely used in enterprise applications.
Happy Learning! 🚀

Comments
Post a Comment