Skip to main content

25+ Spring Data JPA Interview Questions with Answers, Explanations & Use Cases

 

📘 Spring Data JPA Interview Questions (with Answers, Explanations & Use Cases)

spring data jpa interview question answer



1. What is JPA and how is it related to Spring Data JPA?

Answer:
JPA (Java Persistence API) is a Java specification for managing relational data. Spring Data JPA is a part of Spring Data that simplifies JPA usage by reducing boilerplate code.

Use Case:
Persisting Java objects (like User) to a relational database without writing SQL.


2. What are the key annotations used in JPA?

Answer:
@Entity, @Table, @Id, @GeneratedValue, @Column, @ManyToOne, @OneToMany, etc.

Explanation:
These annotations map Java objects to database tables and relationships.

Use Case:
Creating a User entity with an auto-generated ID and fields mapped to table columns.


3. What is the difference between JPA and Hibernate?

Answer:
JPA is a specification; Hibernate is an implementation of that specification.

Use Case:
Using Hibernate as the default JPA provider in Spring Boot.


4. How do you define a primary key in JPA?

Answer:
Using @Id and optionally @GeneratedValue.

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

Use Case:
Auto-generating unique IDs for each database row.


5. What is the purpose of JpaRepository?

Answer:
It is a Spring Data interface that provides CRUD, pagination, and custom query functionality.

Use Case:
Interacting with the User entity without writing any DAO implementation.


6. Difference between CrudRepository and JpaRepository?

Answer:
JpaRepository extends CrudRepository and adds JPA-specific features like flushing and batch operations.

Use Case:
Use JpaRepository for advanced operations like pagination and batch inserts.


7. How do you define custom queries in Spring Data JPA?

Answer:
Using @Query annotation.

@Query("SELECT u FROM User u WHERE u.email = ?1") User findByEmail(String email);

Use Case:
Fetch a user by email using JPQL.


8. How do you write native SQL queries?

Answer:
Use @Query with nativeQuery = true.

@Query(value = "SELECT * FROM users WHERE status = ?1", nativeQuery = true) List<User> findByStatus(String status);

9. What is the difference between JPQL and native SQL?

Answer:
JPQL uses entity names and fields; native SQL uses actual table and column names.

Use Case:
JPQL for portability; native SQL for performance optimization.


10. What is FetchType.LAZY vs EAGER?

Answer:

  • LAZY: Loads associations only when accessed.

  • EAGER: Loads associations immediately.

Use Case:
Avoid performance issues by using LAZY on large data sets.


11. How do you implement one-to-many relationship in JPA?

Answer:

@OneToMany(mappedBy = "user") private List<Order> orders;

Use Case:
A User having multiple Order entries.


12. How to perform pagination and sorting?

Answer:
Use Pageable and Sort in repository methods.

Page<User> findAll(Pageable pageable);

Use Case:
Display paginated results on a web page.


13. How to use projections in Spring Data JPA?

Answer:
By using interfaces or DTOs to return partial data.

interface UserSummary { String getName(); String getEmail(); }

Use Case:
Return only needed fields to reduce bandwidth.


14. What is a DTO and why is it used in JPA?

Answer:
DTO (Data Transfer Object) is used to transfer specific data between layers.

Use Case:
Improve performance and security by not exposing entire entities.


15. What is optimistic locking in JPA?

Answer:
Prevents data loss by using @Version to detect concurrent modifications.

Use Case:
Avoid overwriting changes in concurrent updates.


16. How do you handle bidirectional relationships?

Answer:
Use mappedBy to define the owning side.

Use Case:
Maintain relationship between User and Order with clear ownership.


17. How to prevent the N+1 select problem?

Answer:
Use @EntityGraph or fetch joins.

@Query("SELECT u FROM User u JOIN FETCH u.orders") List<User> findAllWithOrders();

18. What is cascading in JPA?

Answer:
Allows operations to propagate to related entities using cascade = CascadeType.ALL.

Use Case:
Persist or delete child entities automatically.


19. What is save() vs saveAndFlush()?

Answer:

  • save(): Persists entity but may delay DB write.

  • saveAndFlush(): Immediately flushes changes.

Use Case:
Use saveAndFlush() when immediate DB sync is needed.


20. How to enable JPA auditing?

Answer:
Use @CreatedDate, @LastModifiedDate, and @EnableJpaAuditing.

Use Case:
Track creation and update timestamps automatically.


21. What are derived query methods?

Answer:
Methods like findByFirstNameAndLastName() are automatically implemented by Spring.

Use Case:
Avoid writing explicit queries.


22. How to update an entity in Spring Data JPA?

Answer:
Fetch, modify, and then call save().

User user = userRepository.findById(id).get(); user.setEmail("new@example.com"); userRepository.save(user);

23. What is @Modifying and when is it needed?

Answer:
Used with @Query for update/delete operations.

@Modifying @Query("UPDATE User u SET u.status = ?1 WHERE u.id = ?2") void updateStatus(String status, Long id);

24. Can you use Spring Data JPA without Spring Boot?

Answer:
Yes, but Spring Boot simplifies configuration with auto-setup.


25. What is the role of EntityManager in JPA?

Answer:
It provides APIs for CRUD operations and query execution manually.

Use Case:
Used in custom repository implementations.

Comments

Popular posts from this blog

How to Send Emails in Spring Boot Using SMTP (With and Without Attachments)

Sending emails is a common requirement in modern web applications — for things like user registration, password resets, or notifications. In this tutorial, we’ll walk through how to send emails in a Spring Boot application using SMTP , specifically with Gmail’s SMTP server , and demonstrate how to send both plain emails and emails with attachments . 📺 Video Demo If you prefer watching over reading, here’s a full demo of this tutorial in action: 📁 GitHub Repo  Want the complete working code? Clone the GitHub link provided below which contains all the source code. Source Code GitHub Link: https://github.com/TheDipDeveloper/Spring-Boot-Sending-Email 🧰 Prerequisites Java 17 or above Maven Spring Boot 3.x A Gmail account  🚀 Step 1: Add Spring Boot Mail Dependency First, add all the required dependency on pom.xml file < dependencies > < dependency > < groupId >org.springframework.boot</ groupId > < artifactId >spring...

Create a Real-World Banking System with Spring Boot 3, JPA, MySQL & Postman

Are you looking to build a real-world project using Spring Boot and MySQL? In this tutorial, we'll walk you through creating a complete Banking Service REST API that supports full CRUD operations, money transfers, deposits, and withdrawals. Whether you're preparing for interviews or enhancing your portfolio, this hands-on project will give you practical experience with Spring Boot 3, Spring Data JPA, and RESTful API design. In this post, you'll learn how to build a Banking Service REST API using: ✅ Spring Boot 3.x ✅ Java 17 ✅ MySQL ✅ Postman for API testing ✅ IntelliJ IDEA ✅ GitHub Repo : https://github.com/TheDipDeveloper/Banking-Service-Application-REST-Api By the end, you'll have a complete backend application that supports: Creating bank accounts Fetching account data Deposits and withdrawals Transferring funds between accounts Deleting accounts 🛠️ Tech Stack Java 17 Spring Boot 3.x Spring Data JPA MySQL Lombok ...