Backend
5/22/2026
4 min read

Mastering Spring Data JPA – Beginner to Advanced Guide with Real-World Examples

Mastering Spring Data JPA – Beginner to Advanced Guide with Real-World Examples

When building backend applications using Java and Spring Boot, database operations become one of the most repetitive and time-consuming parts of development. Writing SQL queries, handling JDBC connections, mapping rows to Java objects, and managing transactions manually can quickly increase project complexity.

This is where Spring Data JPA becomes extremely useful.

Spring Data JPA reduces boilerplate code and helps developers interact with relational databases using simple Java methods instead of writing large amounts of SQL manually. It sits on top of JPA (Java Persistence API) and commonly uses Hibernate as the implementation provider.

In this article, we will build a simple Employee Management module to understand how Spring Data JPA works in real applications.

What is Spring Data JPA?

Spring Data JPA is a Spring framework module that simplifies database access in Java applications.

Instead of writing DAO implementations manually, Spring Data JPA allows developers to:

  • Save records

  • Fetch data

  • Update records

  • Delete data

  • Perform pagination

  • Write custom queries

using repository interfaces.

Real-World Example

Suppose you are developing an HR Management System.

You need features like:

  • Add employees

  • Fetch employee details

  • Update employee salary

  • Delete employee records

  • Search employees by department

Without Spring Data JPA, this would require a large amount of JDBC code.

With Spring Data JPA, most operations are handled automatically.

Project Dependencies

Add the following dependencies inside your pom.xml.

<dependencies>

<!-- Spring Boot Starter Data JPA -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>

<!-- MySQL Driver -->
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
<scope>runtime</scope>
</dependency>

<!-- Spring Boot Starter Web -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>

</dependencies>

Configure Database

Inside application.properties:

spring.datasource.url=jdbc:mysql://localhost:3306/company_db
spring.datasource.username=root
spring.datasource.password=root

spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.format_sql=true

Create Employee Entity

An Entity represents a database table.

packagecom.ayshriv.entity;

importjakarta.persistence.*;

@Entity
@Table(name="employees")
publicclassEmployee {

    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
privateLongid;

privateStringname;

privateStringdepartment;

privateDoublesalary;

publicEmployee() {
    }

publicEmployee(Stringname,Stringdepartment,Doublesalary) {
this.name=name;
this.department=department;
this.salary=salary;
    }

publicLonggetId() {
returnid;
    }

publicStringgetName() {
returnname;
    }

publicStringgetDepartment() {
returndepartment;
    }

publicDoublegetSalary() {
returnsalary;
    }

publicvoidsetName(Stringname) {
this.name=name;
    }

publicvoidsetDepartment(Stringdepartment) {
this.department=department;
    }

publicvoidsetSalary(Doublesalary) {
this.salary=salary;
    }
}

Create Repository Interface

This is the most powerful feature of Spring Data JPA.

packagecom.ayshriv.repository;

importcom.ayshriv.entity.Employee;
importorg.springframework.data.jpa.repository.JpaRepository;

publicinterfaceEmployeeRepositoryextendsJpaRepository<Employee,Long> {

}

Here:

  • Employee → Entity class

  • Long → Primary key type

By extending JpaRepository, Spring automatically provides methods like:

  • save()

  • findById()

  • findAll()

  • deleteById()

  • count()

No implementation class is required.

Create Service Layer

packagecom.ayshriv.service;

importcom.ayshriv.entity.Employee;
importcom.ayshriv.repository.EmployeeRepository;
importorg.springframework.stereotype.Service;

importjava.util.List;

@Service
publicclassEmployeeService {

privatefinalEmployeeRepositoryemployeeRepository;

publicEmployeeService(EmployeeRepositoryemployeeRepository) {
this.employeeRepository=employeeRepository;
    }

publicEmployeesaveEmployee(Employeeemployee) {
returnemployeeRepository.save(employee);
    }

publicList<Employee>getAllEmployees() {
returnemployeeRepository.findAll();
    }
}

Create REST Controller

packagecom.ayshriv.controller;

importcom.ayshriv.entity.Employee;
importcom.ayshriv.service.EmployeeService;
importorg.springframework.web.bind.annotation.*;

importjava.util.List;

@RestController
@RequestMapping("/employees")
publicclassEmployeeController {

privatefinalEmployeeServiceemployeeService;

publicEmployeeController(EmployeeServiceemployeeService) {
this.employeeService=employeeService;
    }

    @PostMapping
publicEmployeesaveEmployee(@RequestBodyEmployeeemployee) {
returnemployeeService.saveEmployee(employee);
    }

    @GetMapping
publicList<Employee>getAllEmployees() {
returnemployeeService.getAllEmployees();
    }
}

Test API

Save Employee

POST Request

POST /employees

Request Body

{
  "name":"Rahul Sharma",
  "department":"IT",
  "salary":65000
}

Fetch Employees

GET Request

GET /employees

Response

[
  {
    "id":1,
    "name":"Rahul Sharma",
    "department":"IT",
    "salary":65000
  }
]

How Spring Data JPA Works Internally

In the above code:

  1. Spring Boot scans the repository interface.

  2. Spring creates a proxy implementation automatically.

  3. Hibernate converts entity objects into SQL queries.

  4. SQL executes on the MySQL database.

  5. Response data is mapped back into Java objects.

This entire process happens automatically.

Advantages of Spring Data JPA

1. Less Boilerplate Code

No need to write JDBC code manually.

2. Faster Development

Most CRUD operations are already available.

3. Better Maintainability

Cleaner project structure and reusable repositories.

4. Database Independent

Code remains mostly unchanged even if the databases change.

5. Integration with Spring Boot

Works smoothly with transactions, validation, security, and REST APIs.

Commonly Used JpaRepository Methods

Method

Description

save()

Insert or update record

findById()

Fetch single record

findAll()

Fetch all records

deleteById()

Delete record

count()

Count total rows

existsById()

Check record existence

Conclusion

Spring Data JPA makes database interaction significantly easier in Spring Boot applications. Instead of writing repetitive SQL and DAO code, developers can focus on business logic and application features.

In this article, we created a simple Employee Management module using:

  • Entity

  • Repository

  • Service

  • REST Controller

This is the foundation of almost every production-level Spring Boot application.

In the next article, we will explore:

Derived Query Methods in Spring Data JPA

Learn how to create dynamic queries simply by writing method names like:

findByDepartment()
findBySalaryGreaterThan()
findByNameContaining()

without writing SQL manually.

Enjoyed this article?

Subscribe to our newsletter for more backend engineering insights and tutorials.