Category: spring_boot
Spring Data JPA
Published on 26 Jun 2026
Explanation
Spring Data JPA simplifies
database operations
by providing ready-to-use
CRUD methods through
the JpaRepository interface.
Developers can focus
on business logic instead of writing
SQL queries.
Code:
import org.springframework.data.jpa.
repository.JpaRepository;
public interface StudentRepository
extends JpaRepository<Student, Long> {
}
Explanation
To perform CRUD operations, first create
an Entity class that represents a
database table. The @Entity annotation maps
the class to a table in
the database.
Code:
@Entity
public class Student {
@Id
@GeneratedValue(strategy =
GenerationType.IDENTITY)
private Long id;
private String name;
private String email;
// Getters and Setters
}
Explanation
The save() method is used to
create new records in the database.
If the primary key does not
exist, Spring Data JPA performs an
INSERT operation.
Code:
@PostMapping
public Student createStudent(
@RequestBody Student student) {
return studentRepository.save(student);
}
Explanation
The findAll() and findById() methods are
used to retrieve records from the
database. These methods are
provided automatically
by JpaRepository.
Code:
@GetMapping
public List<Student> getStudents() {
return studentRepository.findAll();
}
@GetMapping("/{id}")
public Student getStudent(
@PathVariable Long id) {
return studentRepository.
findById(id).orElse(null);
}
Explanation
The save() method can also update
existing records, while deleteById()
removes records
from the database. If the ID
exists, save() performs an
UPDATE operation.
Code:
@PutMapping("/{id}")
public Student updateStudent(
@PathVariable Long id,
@RequestBody Student student) {
student.setId(id);
return studentRepository.save(student);
}
@DeleteMapping("/{id}")
public String deleteStudent(
@PathVariable Long id) {
studentRepository.deleteById(id);
return "Student deleted successfully";
}