Spring Data Jpa Sample Code 2025
Spring Data Jpa Sample Code 2025
➢ Spring Data is an umbrella project that contains multiple sub-projects for data access,
supporting multiple types of databases (both relational, NoSQL databases like
MongoDB). This reduces the amount of boilerplate code developers need to write.
➢ Spring Data JPA is a module within the Spring Data project specifically designed to
simplify JPA (Java Persistence API) access.
➢ JPA is a specification for data access in Java applications, specifically designed for
object-relational mapping (ORM).
➢ Hibernate (ORM tool) is a popular implementation of the JPA specification.
➢ JPA Repository simplifies and replaces the need for a custom DAO pattern.still DAO
can be used
Example of JPA Providers (Implementations):
✓ Hibernate
✓ EclipseLink
✓ OpenJPA
Spring Data JPA
Advantages
1. Spring Web
2. Spring Data JPA
3. MySQL Driver
4. Lombok (Optional)
1. controller
2. service
3. repository
4. entity
o Define a class annotated with @Entity use @Id and @GeneratedValue to define the
primary key.
o Extend the JpaRepository interface for the entity to enable built-in CRUD
operations.
o Define a service interface and a ServiceImpl class which Implement the service
interface for business logic
7. Create a Controller
o Create a REST controller to define endpoints for CRUD operations. Use annotations
like @GetMapping, @PostMapping, @PutMapping, and @DeleteMapping.
Start the application and test it with use tools like Postman, cURL, or a browser to
test the API endpoints.
// Application Entry Point
package com.example;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class DemoApplication {
application.properties
spring.datasource.url=jdbc:mysql://localhost:3306/testdb
spring.datasource.username=root
spring.datasource.password=root
spring.jpa.hibernate.ddl-auto=update
Employee Entity
package com.example.entity;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
@Entity
public class Employee {
@Id
// @GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
// Constructors getters and setters
public Employee() {
}
//Employee Repository
package com.example.repository;
import com.example.demo.entity.Employee;
import org.springframework.data.jpa.repository.JpaRepository;
package com.example.controller;
import com.example.demo.entity.Employee;
import com.example.demo.repository.EmployeeRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping(“/api”)
public class EmployeeController {
@Autowired
private EmployeeRepository repository;
// Get employee by ID
@GetMapping("/employees/{id}")
public Employee getEmployeeById(@PathVariable Long id)
{
return repository.findById(id).orElseThrow(() -> new RuntimeException("Employee not
found"));
}
Api endpoints
Operation HTTP Method Complete URL Request Body
Get all employees GET /api/employees None
Create a new employee POST /api/employees { "name": "Tom" }
Get employee by ID GET /api/employees/{id} None
Update an existing employee PUT /api/employees/{id} { "name": "Tom Updated" }
Delete an employee DELETE /api/employees/{id} None
If you want to user Service and ServiceImpl
package com.example.service;
import com.example.entity.Employee;
import java.util.List;
List<Employee> getAllEmployees();
package com.example.service;
import com.example.entity.Employee;
import com.example.repository.EmployeeRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class EmployeeServiceImpl implements EmployeeService {
@Autowired
private EmployeeRepository repository;
@Override
public List<Employee> getAllEmployees()
{
return repository.findAll();
}
@Override
public Employee getEmployeeById(Long id)
{
return repository.findById(id).orElseThrow(() -> new RuntimeException("Employee not
found"));
// return repository.findById(id).orElse(null);
}
@Override
public Employee createEmployee(Employee employee)
{
return repository.save(employee);
}
Note: the updateEmployee() can be written like this as well using map() as well
@Override
public Employee updateEmployee(Long id, Employee updatedEmp) {
return repository.findById(id).map(employee -> {
employee.setName(updatedEmp.getName());
return repository.save(employee);
}).orElseThrow(() -> new RuntimeException("Employee not found"));
}
// Employee Controller using Service
package com.example.controller;
import com.example.entity.Employee;
import com.example.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping(“/api”)
public class EmployeeController {
// You need to modify the controller injecting the employeeService instead of repository
@Autowired
private EmployeeService employeeService;
@GetMapping("/employees")
public List<Employee> getAllEmployees() {
return employeeService.getAllEmployees();
}
@PostMapping("/employees")
public Employee createEmployee(@RequestBody Employee employee) {
return employeeService.createEmployee(employee);
}
// Get employee by ID
@GetMapping("/employees/{id}")
public Employee getEmployeeById(@PathVariable Long id) {
return employeeService.getEmployeeById(id);
}
@PutMapping("/employees/{id}")
public Employee updateEmployee(@PathVariable Long id, @RequestBody Employee
updatedEmployee) {
return employeeService.updateEmployee(id, updatedEmployee);
}
@DeleteMapping("/employees/{id}")
public String deleteEmployee(@PathVariable Long id) {
employeeService.deleteEmployee(id);
return "Employee deleted successfully";
}
}
Controller Using ResponseEntity with
package com.example.demo.controller;
import com.example.demo.entity.Employee;
import com.example.demo.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping(“/api”)
public class EmployeeController {
@Autowired
private EmployeeService employeeService;
// Get an employee by ID
@GetMapping("/employees/{id}")
public ResponseEntity<Employee> getEmployeeById(@PathVariable Long id) {
Employee employee = employeeService.getEmployeeById(id);
return ResponseEntity.ok(employee);
}
// Delete an employee
@DeleteMapping("/employees/{id}")
public ResponseEntity<String> deleteEmployee(@PathVariable Long id) {
employeeService.deleteEmployee(id);
return ResponseEntity.ok("Employee deleted successfully.");
//return ResponseEntity.noContent().build();
}
}
HTTP
Operation Complete URL Request Body Response Code
Method
Get all
GET http://localhost:8080/api/employees None 200 OK
employees
Get
200 OK (if found), 404
employee by GET http://localhost:8080/api/employees/{id} None
Not Found (if not found)
ID
Update { "name":
200 OK (if found), 404
employee by PUT http://localhost:8080/api/employees/{id} "Tom
Not Found (if not found)
ID Updated" }
2) Using map()
@PutMapping("/{id}")
public Employee updateEmployee(@PathVariable Long id, @RequestBody Employee
updatedEmp) {
return repository.findById(id).map(employee -> {
employee.setName(updatedEmp.getName());
return repository.save(employee);
}).orElseThrow(() -> new RuntimeException("Employee not found"));
}
3)Using optional
public Optional<Employee> updateEmployee(@PathVariable Long id, @RequestBody Employee
updatedEmp) {
Optional<Employee> optionalEmpl = repository.findById(id);
if (optionalEmp.isPresent()) {
Employee employee = optionalEmp.get();
employee.setName(updatedEmp.getName());
return Optional.of(repository.save(employee));
}
return Optional.empty();
}