Spring Boot - CRUD Operations

Last Updated : 14 Mar, 2026

In Spring Boot, CRUD operations represent the basic actions performed to manage data in an application’s database. These operations allow developers to store, retrieve, modify, and remove data efficiently. Spring Boot simplifies database interaction by integrating tools like Spring Data JPA and ORM frameworks such as Hibernate ORM, which reduce the need for writing large amounts of boilerplate code.

  • Provides an easy way to build RESTful APIs that interact with databases.
  • Reduces development effort by offering ready-to-use repository interfaces.
  • Integrates seamlessly with relational databases like MySQL, PostgreSQL, and others.

CRUD Operations

CRUD operations are the four basic operations used to manage data in a database within an application. In Spring Boot, CRUD operations are commonly implemented using Spring Data JPA to interact with the database easily.

CRUD Operations are:

  • Create: Used to add new data or records into the database.
  • Read: Used to retrieve or fetch data from the database.
  • Update: Used to modify or change existing data in the database.
  • Delete: Used to remove data or records from the database.
CRUD Operation

As the name suggests, 

  • CREATE Operation: Performs the INSERT statement to create a new record.
  • READ Operation: Reads table records based on the input parameter.
  • UPDATE Operation: Executes an update statement on the table. It is based on the input parameter.
  • DELETE Operation: Deletes a specified row in the table. It is also based on the input parameter.

H2 Database

H2 is a relational database management system written in Java. It can be embedded in Java applications or run in client-server mode. The main features of H2 are:

  • Very fast, open-source, JDBC API
  • Embedded and server modes; in-memory databases
  • Browser-based Console application
  • Small footprint: around 2.5 MB jar file size

Spring Boot CrudRepository

In Spring Boot, CrudRepository is an interface provided by Spring Data JPA that allows developers to perform basic database operations without writing SQL queries. It provides built-in methods to easily interact with the database.

  • Provides predefined methods like save(), findById(), findAll(), and deleteById().
  • Reduces boilerplate code and simplifies database interaction in Spring Boot applications.

Syntax:

public interface DepartmentRepository extends CrudRepository<Department, Long> { }

Where:

  • Department : The entity/model class that the repository manages.
  • Long :The data type of the entity’s @Id field.

Spring Boot JpaRepository

Java Persistence API is a specification used to manage relational data in Java applications. In Spring Data JPA, JpaRepository is an extension of CrudRepository that provides additional database operation methods.

  • Supports basic CRUD operations along with pagination and sorting features.
  • Provides JPA-specific methods like flushing the persistence context and deleting records in batch.
repository

Syntax:

public interface JpaRepository<T, ID> extends PagingAndSortingRepository<T, ID>, QueryByExampleExecutor<T>


Steps for Implementing CRUD Operations

Step1: Create a Spring Boot project .

Add the following dependency

Below is the complete code for the pom.xml file.

XML
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="https://maven.apache.org/POM/4.0.0" xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="https://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.5.5</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.amiya</groupId>
    <artifactId>Spring-Boot-Demo-Project</artifactId>
    <version>1.0.0-SNAPSHOT</version>
    <name>Spring-Boot-Demo-Project</name>
    <description>Demo project for Spring Boot</description>
    <properties>
        <java.version>11</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>com.h2database</groupId>
            <artifactId>h2</artifactId>
            <scope>runtime</scope>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>

    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <excludes>
                        <exclude>
                            <groupId>org.projectlombok</groupId>
                            <artifactId>lombok</artifactId>
                        </exclude>
                    </excludes>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>

Step 2: Project Structure

  • entity
  • repository
  • service
  • controller
Directory Structure

Note:

  • Green Rounded Icon 'I' Buttons are Interface
  • Blue Rounded Icon 'C' Buttons are Classes

Step 3: Inside Entity class

Create a simple POJO class inside the Department.java file. 

Example

Java
// Java Program to Illustrate Department.java File

// Importing required package modules
package com.amiya.springbootdemoproject.entity;

// Importing required classes
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;

@Entity
@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder

// Class
public class Department {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long departmentId;
    private String departmentName;
    private String departmentAddress;
    private String departmentCode;
}

Step 4: Inside the Repository package

Create a simple interface and name the interface as DepartmentRepository. This interface is going to extend the CrudRepository as we have discussed above. Below is the code for the DepartmentRepository.java file

Example

Java
package com.amiya.springbootdemoproject.repository;

import com.amiya.springbootdemoproject.entity.Department;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;

@Repository
public interface DepartmentRepository extends CrudRepository<Department, Long> {
    
}

Step 5: Inside the Service package

Inside the package create one interface named as DepartmentService and one class named as DepartmentServiceImpl.

Example 1

Java
// Java Program to Illustrate DepartmentService.java File

// Importing packages
package com.amiya.springbootdemoproject.service;
import com.amiya.springbootdemoproject.entity.Department;
// Importing required classes
import java.util.List;

// Class
public interface DepartmentService {

    // Save operation
    Department saveDepartment(Department department);

    // Read operation
    List<Department> fetchDepartmentList();

    // Update operation
    Department updateDepartment(Department department,
                                Long departmentId);

    // Delete operation
    void deleteDepartmentById(Long departmentId);
}

Below is the code for the DepartmentServiceImpl.java file

Example 2

Java
// Java Program to Illustrate DepartmentServiceImpl.java
// File

// Importing required packages
package com.amiya.springbootdemoproject.service;

import com.amiya.springbootdemoproject.entity.Department;
import com.amiya.springbootdemoproject.repository.DepartmentRepository;
// Importing required classes
import java.util.List;
import java.util.Objects;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

// Annotation
@Service
// Class implementing DepartmentService class
public class DepartmentServiceImpl
    implements DepartmentService {

    @Autowired
    private DepartmentRepository departmentRepository;

    // Save operation
    @Override
    public Department saveDepartment(Department department)
    {
        return departmentRepository.save(department);
    }

    // Read operation
    @Override public List<Department> fetchDepartmentList()
    {
        return (List<Department>)
            departmentRepository.findAll();
    }

    // Update operation
    @Override
    public Department
    updateDepartment(Department department,
                     Long departmentId)
    {

        Department depDB
            = departmentRepository.findById(departmentId)
                  .get();

        if (Objects.nonNull(department.getDepartmentName())
            && !"".equalsIgnoreCase(
                department.getDepartmentName())) {
            depDB.setDepartmentName(
                department.getDepartmentName());
        }

        if (Objects.nonNull(
                department.getDepartmentAddress())
            && !"".equalsIgnoreCase(
                department.getDepartmentAddress())) {
            depDB.setDepartmentAddress(
                department.getDepartmentAddress());
        }

        if (Objects.nonNull(department.getDepartmentCode())
            && !"".equalsIgnoreCase(
                department.getDepartmentCode())) {
            depDB.setDepartmentCode(
                department.getDepartmentCode());
        }

        return departmentRepository.save(depDB);
    }

    // Delete operation
    @Override
    public void deleteDepartmentById(Long departmentId)
    {
        departmentRepository.deleteById(departmentId);
    }
}

Step 6: Inside the Controller package

Create one class named as DepartmentController

Java
// Java Program to Illustrate DepartmentController.java File

// Importing packages modules
package com.amiya.springbootdemoproject.controller;

import com.amiya.springbootdemoproject.entity.Department;
import com.amiya.springbootdemoproject.service.DepartmentService;
import java.util.List;
// Importing required classes
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

// Annotation
@RestController
// Class
public class DepartmentController {

    @Autowired private DepartmentService departmentService;

    // Save operation
    @PostMapping("/departments")

    public Department saveDepartment(
        @Valid @RequestBody Department department)
    {
        return departmentService.saveDepartment(department);
    }

    // Read operation
    @GetMapping("/departments")

    public List<Department> fetchDepartmentList()
    {
        return departmentService.fetchDepartmentList();
    }

    // Update operation
    @PutMapping("/departments/{id}")

    public Department
    updateDepartment(@RequestBody Department department,
                     @PathVariable("id") Long departmentId)
    {
        return departmentService.updateDepartment(
            department, departmentId);
    }

    // Delete operation
    @DeleteMapping("/departments/{id}")

    public String deleteDepartmentById(@PathVariable("id")
                                       Long departmentId)
    {
        departmentService.deleteDepartmentById(
            departmentId);
        return "Deleted Successfully";
    }
}

Step 7: Setting application.properties file

server.port = 8082 # H2 Database spring.h2.console.enabled=true spring.datasource.url=jdbc:h2:mem:dcbapp spring.datasource.driverClassName=org.h2.Driver spring.datasource.username=sa spring.datasource.password=password spring.jpa.database-platform=org.hibernate.dialect.H2Dialect

Now run your application and let's test the endpoints in Postman and also refer to our H2 Database.

Testing the Endpoint in Postman

Endpoint 1: POST - http://localhost:8082/departments/

Endpoint 2: GET - http://localhost:8082/departments/

Endpoint 3: PUT - http://localhost:8082/departments/1

Endpoint 4: DELETE - http://localhost:8082/departments/1

Lastly, H2 Database is as depicted in the below media as follows:

H2_Database_image
Comment