Spring Data JPA is one of the most popular modules in the Spring ecosystem. It simplifies database operations by reducing boilerplate code and providing ready-made repository implementations.

Instead of writing lengthy JDBC code, developers can use Spring Data JPA repositories to perform Create, Read, Update and Delete (CRUD) operations with minimal effort.
What is Spring Data JPA?
Spring Data JPA is a framework built on top of JPA (Java Persistence API) that simplifies database access in Spring applications.
It provides repository interfaces that automatically generate SQL queries behind the scenes.
Why Use Spring Data JPA?
- Less boilerplate code
- Automatic query generation
- Built-in CRUD methods
- Pagination support
- Sorting support
- Easier database access
Project Structure
src/main/java
├── controller
│ └── EmployeeController
│
├── service
│ └── EmployeeService
│
├── repository
│ └── EmployeeRepository
│
├── entity
│ └── Employee
│
└── EmployeeApplication
Step 1: Maven Dependencies
Add the required dependencies in pom.xml.
<dependency>
<groupId>
org.springframework.boot
</groupId>
<artifactId>
spring-boot-starter-data-jpa
</artifactId>
</dependency>
<dependency>
<groupId>
com.mysql
</groupId>
<artifactId>
mysql-connector-j
</artifactId>
</dependency>
<dependency>
<groupId>
org.springframework.boot
</groupId>
<artifactId>
spring-boot-starter-web
</artifactId>
</dependency>
Step 2: Configure Database
Create application.properties.
spring.datasource.url=
jdbc:mysql://localhost:3306/employeedb
spring.datasource.username=root
spring.datasource.password=root
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
Step 3: Create Entity Class
The Entity class represents a database table.
@Entity
@Table(name = "employees")
public class Employee {
@Id
@GeneratedValue(
strategy =
GenerationType.IDENTITY
)
private Long id;
private String name;
private String department;
private Double salary;
public Employee() {
}
public Employee(
String name,
String department,
Double salary) {
this.name = name;
this.department = department;
this.salary = salary;
}
// Getters and Setters
}
What Do These Annotations Mean?
| Annotation | Purpose |
|---|---|
| @Entity | Marks class as database entity |
| @Table | Maps to database table |
| @Id | Primary key |
| @GeneratedValue | Auto-generates ID |
Step 4: Create Repository Layer
The Repository layer handles database communication.
@Repository
public interface EmployeeRepository
extends JpaRepository<
Employee,
Long> {
}
That's it.
Spring automatically provides CRUD methods.
Available CRUD Methods
save()
findById()
findAll()
deleteById()
count()
existsById()
Step 5: Create Service Layer
Business logic belongs in the service layer.
@Service
public class EmployeeService {
private final
EmployeeRepository repository;
public EmployeeService(
EmployeeRepository repository) {
this.repository = repository;
}
public Employee saveEmployee(
Employee employee) {
return repository.save(
employee);
}
public List<Employee>
getEmployees() {
return repository.findAll();
}
public Employee getEmployee(
Long id) {
return repository
.findById(id)
.orElseThrow();
}
public void deleteEmployee(
Long id) {
repository.deleteById(id);
}
}
Step 6: Create REST Controller
The Controller exposes API endpoints.
@RestController
@RequestMapping("/employees")
public class EmployeeController {
private final
EmployeeService service;
public EmployeeController(
EmployeeService service) {
this.service = service;
}
@PostMapping
public Employee createEmployee(
@RequestBody Employee employee) {
return service.saveEmployee(
employee);
}
@GetMapping
public List<Employee>
getEmployees() {
return service.getEmployees();
}
@GetMapping("/{id}")
public Employee getEmployee(
@PathVariable Long id) {
return service.getEmployee(id);
}
@DeleteMapping("/{id}")
public void deleteEmployee(
@PathVariable Long id) {
service.deleteEmployee(id);
}
}
Testing Create Employee API
POST Request:
POST /employees
Request Body:
{
"name":"John",
"department":"IT",
"salary":50000
}
Response:
{
"id":1,
"name":"John",
"department":"IT",
"salary":50000
}
Testing Get All Employees
GET /employees
Response
[
{
"id":1,
"name":"John",
"department":"IT"
}
]
Custom Query Method Example
Spring Data JPA can generate queries directly from method names.
List<Employee>
findByDepartment(
String department
);
Spring automatically generates the SQL query.
Generated Query Conceptually
SELECT *
FROM employees
WHERE department = ?
Common Interview Questions
What is Spring Data JPA?
A framework that simplifies database operations using JPA repositories.
What is JpaRepository?
An interface that provides built-in CRUD operations.
Difference Between JPA and Hibernate?
JPA is a specification. Hibernate is one implementation of JPA.
What does @Entity do?
Marks a class as a database entity.
Can we create custom queries?
Yes, using method names, JPQL or native SQL queries.
Best Practices
- Keep business logic in service layer.
- Avoid database logic in controllers.
- Use constructor injection.
- Create custom queries only when needed.
- Use pagination for large datasets.
Frequently Asked Questions (FAQ)
Does Spring Data JPA create tables automatically?
Yes, when Hibernate DDL auto generation is enabled.
Can Spring Data JPA work with PostgreSQL?
Yes. It supports PostgreSQL, MySQL, Oracle, SQL Server and many other databases.
Is Hibernate required?
Hibernate is the default JPA implementation in Spring Boot applications.
Conclusion
Spring Data JPA drastically reduces database-related boilerplate code and allows developers to focus on business logic. Understanding Entities, Repositories, Services, Controllers and CRUD operations is essential for building Spring Boot applications and succeeding in Spring interviews.
Keywords
Spring Data JPA, Spring Boot CRUD Example, JpaRepository Example, Spring JPA Tutorial, Hibernate JPA, Spring Boot Database Example, Spring Boot REST API, CRUD Operations Spring Boot, JPA Interview Questions, Spring Data JPA Tutorial, Entity Repository Service Controller, Java Persistence API, Spring Framework, Spring Boot Example, Java Backend Development
Reviewed by 13thGhost
on
2:53 AM
Rating:
No comments: