Implement CRUD Operations using Spring Boot

Overview

In this tutorial, we will explain step-by-step everything how to implement CRUD (CREATE, READ, UPDATE, DELETE) Operations using Spring Boot, Jpa, and MySQL. Follow these steps to implement complete CRUD Operations.

Implement CRUD Operations using Spring boot

Table of Contents:

  • Introduction about CRUD (CREATE, READ, UPDATE, DELETE) Operations
  • Understand about the MVC Pattern or Architecture for creating rest apis
  • Set up the Spring Boot application (server).
  • Configure the application.properties file to connect the database.
  • Create REST APIs using Spring Boot for CRUD operations (CREATE, READ, UPDATE,DELETE)
  • Run the application and test apis using postman

CRUD (create, read, update delete) Operations

Method API URL Description
GET http://localhost:port/endpoint Get all the data
GET http://localhost:port/endpoint/{id} Get single data based on ID
POST http://localhost:port/endpoint Add new data
PUT http://localhost:port/endpoint Update data
DELETE http://localhost:port/endpoint/{id} Delete data based on ID

Before creating an APIs let’s understand about the MVC Pattern or Architecture for creating rest apis

MVC pattern for Creating rest apis using spring boot

Source – geeksforgeeks

Now let’s implement APIs for CRUD operations in systematic way

Step 1: Set Up Your Spring Boot Application

Use Spring Initializer or an IDE like IntelliJ or Eclipse to create a new Spring Boot project. Add the following dependencies:

  • Spring Web: For building web applications and REST APIs.
  • Spring Data JPA: For interacting with the database.
  • MySQL Driver: To connect to your MySQL database.

Step 2: Configure the application.properties File

1. Open the application.properties file and configure your database settings. Here’s an example configuration:

2. Replace your_database_name, your_username, and your_password with your database details.


 # Server configuration
 server.port = 8081
                    
 # Database configuration
 spring.datasource.url=jdbc:mysql://localhost:3306/your_database_name
 spring.datasource.name=your_database_name
 spring.datasource.username=your_username
 spring.datasource.password=your_password
 spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
                    
 # JPA configuration
 spring.jpa.hibernate.ddl-auto=update
                  

For More Details:

If you want to learn more about configuring the application.properties file, check out this detailed article:

Create REST APIs Using Spring Boot: Step-by-Step Guide

Step 3: Create REST APIs Using Spring Boot for CRUD operations (CREATE, READ, UPDATE,DELETE)

Now we going for create REST APIs using Spring Boot for CRUD Operations (Let’s take the example of Student), we need:

  • Entity Classes: Representing the database table.
  • Controller: Defining the endpoints of the API.
  • Service: Containing the business logic.
  • Repository: Performing database operations.

Let’s create each of these components step by step.

Entity Class (Students)


@Entity
public class Students {
	
    @Id
    private int id;
    private String name;
    private int age;
    private String dept;
	
    // Parameterized constructor
    public Students(int id, String name, int age, String dept) {
        super();
        this.id = id;
        this.name = name;
        this.age = age;
        this.dept = dept;
    }
	
    // Non-parameterized constructor
    public Students() {
    }
    
    // Getters and setters
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    public String getDept() {
        return dept;
    }
    public void setDept(String dept) {
        this.dept = dept;
    }
}

Controller (for defining api endpoint)


@RestController
public class StudentController {
	
    @Autowired
    private StudentService studentService;
	
    @PostMapping("/addStudent")
    @CrossOrigin(origins = "http://127.0.0.1:5500")
    public Students addStudent(@RequestBody Students students) {
        return studentService.addStudent(students);
    }
	
    @GetMapping("/getStudents")
    @CrossOrigin(origins = "http://127.0.0.1:5500")
    public List<Students> getAllStudents() {
        return studentService.getAllStudents();
    }
	
    @PostMapping("/updateStudent")
    @CrossOrigin(origins = "http://127.0.0.1:5500")
    public Students updateStudent(@RequestBody Students students) {
        return studentService.udpateStudent(students);
    }
	
    @GetMapping("/deleteStudent/{id}")
    @CrossOrigin(origins = "http://127.0.0.1:5500")
    public Boolean deleteStudent(@PathVariable int id) {
        return studentService.deleteStudent(id);
    }
}

Service


@Service
public class StudentService {
	
    @Autowired
    private StudentRepo studentRepo;

    public Students addStudent(Students student) {
        return studentRepo.save(student);
    }
	
    public List<Students> getAllStudents() {
        return studentRepo.findAll();
    }
	
    public Students udpateStudent(Students updatedStudent) {
        Optional<Students> student1 = studentRepo.findById(updatedStudent.getId());
        Students student = student1.get();
        student.setAge(updatedStudent.getAge());
        student.setDept(updatedStudent.getDept());
        student.setName(updatedStudent.getName());
		
        return studentRepo.save(student);
    }
	
    public Boolean deleteStudent(int id) {
        studentRepo.deleteById(id);
        return true;
    }
}

Repository


import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

import com.crudAPI.example.entity.Students;

@Repository
public interface StudentRepo extends JpaRepository<Students, Integer> {

}

Project Structure

Here’s an image showing the project structure for better understanding.

spring boot project structure for CRUD APIs

Run the Application

Run your Spring Boot application. It will automatically create the database table based on the students entity.

automatic table created

Now let’s test all the apis one-by-one using postman

-> Insert data using api (test- Create api)

Insert api testing

We have insert some data into database using api now let’s check students table data added or not

student table with inserted data

-> Fetch all the data from Student table (test- Read api)

read api testing

-> Update data (test- Update api)

update api testing

-> Delete the data from the table (test- Delete api)

delete api testing

In delete api i have send the id in url and based on the id it will delete the record

Youtube Video –

Github Repository –

https://github.com/amangupta7024/CRUD-Operation-SpringBoot

Explore our more articles

Implement CRUD (create, read, update, delete) operations using spring boot ?

In this tutorial, we will explain step-by-step everything how to implement CRUD (CREATE, READ, UPDATE, DELETE) Operations using Spring Boot, Jpa, and MySQL. Follow these steps to implement complete CRUD Operations.

– Introduction about CRUD (CREATE, READ, UPDATE, DELETE) Operations
– Understand about the MVC Pattern or Architecture for creating rest apis
– Set up the Spring Boot application (server).
– Configure the application.properties file to connect the database.
– Create REST APIs using Spring Boot for CRUD operations (CREATE, READ, UPDATE,DELETE)
– Run the application and test apis using postman

2 thoughts on “Implement CRUD Operations using Spring Boot”

  1. Hi there! I could have sworn I’ve been to this blog before but after browsing through some of the post
    I realized it’s new to me. Nonetheless, I’m definitely glad I found it and I’ll be bookmarking and checking back frequently!

    Also visit my web-site nordvpn Coupons inspiresensation (T.co)

    Reply

Leave a Comment