Hackforge Academy

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";
}

๐Ÿš€ Learn Spring Boot with real-world projects

๐Ÿ’ก Build REST APIs step by step

๐Ÿง  Improve backend development skills

๐ŸŽฏ Get career-ready practical training

Join Our Free WhatsApp Community

Direct access to niche-specific mentors and peers on WhatsApp.

๐Ÿ

Python Community

Discuss Django, FastAPI, AI integration, and automation scripts with 15k+ developers.

Join Python Community
โš›๏ธ

React Community

Master Next.js, Framer Motion, and State Management. Share your latest UI components.

Join React Community
โ˜•

Java Community

Deep dives into Spring Boot, Microservices architecture, and high-performance backend ops.

Join Java Community