Spring Boot - CrudRepository with Example
Last Updated :
27 Aug, 2025
Spring Boot's CrudRepository is a part of the Spring Data JPA framework, which provides convenient methods for performing CRUD (Create, Read, Update, Delete) operations on entities in a relational database. CrudRepository is an interface that extends the basic Repository interface and adds generic CRUD methods to it. It is defined in the package org.springframework.data.repository and it extends the Spring Data Repository interface. If someone wants to use CrudRepository in the Spring Boot application, she has to create an interface and extend the CrudRepository interface.
Syntax:
public interface CrudRepository<T, ID> extends Repository<T, ID>
Where:
- T: Domain type managed by the repository (Entity class).
- ID: Type of the entity's ID (e.g., Long)
Example:
public interface DepartmentRepository extends CrudRepository<Department, Long> {}
Important Methods of CrudRepository:
Now, let us discuss some of the most important methods that are available inside the CrudRepository are given below as follows:
1. save(): Saves a given entity. Use the returned instance for further operations as the save operation might have changed the entity instance completely.
Syntax:
<S extends T> S save(S entity)
- Parameters: entity must not be null.
- Returns: the saved entity; will never be null.
- Throws: IllegalArgumentException in case the given entity is null.
2. findById(): Retrieves an entity by its id.
Syntax:
Optional<T> findById(ID id)
- Parameters: id - must not be null.
- Returns: the entity with the given id or Optional#empty() if none found.
- Exception Thrown: IllegalArgumentException is thrown if the 'id' is null.
3. findAll(): Returns all instances of the type.
Syntax:
Iterable<T> findAll()
Return Type: All entities
4. count(): Returns the number of entities available.
Syntax:
long count()
Return Type: the number of entities.
Method 5: deleteById(): Deletes the entity with the given id.
Syntax:
void deleteById(ID id)
Parameters: Id (must not be null)
Exception Thrown: IllegalArgumentException in case the given id is null.
Example
The following Spring Boot application manages a Department entity with CrudRepository. The data is saved in the H2 database. We use a RESTful controller.
Step 1: Create a Spring Boot Project
Go to Spring Initializr and select:
- Project: Maven
- Language: Java
- Spring Boot: 3.x
- Dependencies: Spring Web, Spring Data JPA, H2 Database, Lombok
Download and open it in your IDE.
Below is the complete code for the pom.xml file. Please check if you have missed something.
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>
# H2 Database
spring.h2.console.enabled=true
spring.h2.console.path=/h2-console
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
spring.jpa.hibernate.ddl-auto=update
Step 3: Create packages
- entity
- repository
- service
- controller

Step 4: Add the entity
Inside the entity package create a simple POJO class inside the Department.java file. Below is the code for the Department.java file
Java
package com.amiya.springbootdemoproject.entity;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
@Entity
@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder
public class Department {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long departmentId;
private String departmentName;
private String departmentAddress;
private String departmentCode;
}
Step 5: Add the repository
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.

Java
package com.amiya.springbootdemoproject.repository;
// Importing required classes
import com.amiya.springbootdemoproject.entity.Department;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
// Annotation
@Repository
// Class
public interface DepartmentRepository
extends CrudRepository<Department, Long> {
}
Step 6: Add the service layer
Inside the package create one interface named as DepartmentService and one class named as DepartmentServiceImpl. Below is the code for the DepartmentService.java file.
Example A
Java
package com.amiya.springbootdemoproject.service;
import com.amiya.springbootdemoproject.entity.Department;
import java.util.List;
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);
}
Example B : Below is the code for the DepartmentServiceImpl.java file.
Java
package com.amiya.springbootdemoproject.service;
import com.amiya.springbootdemoproject.entity.Department;
import com.amiya.springbootdemoproject.repository.DepartmentRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Objects;
@Service
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 7: Add the controller:
Inside the controller package create one class named as DepartmentController.
Java
// Importing package module
package com.amiya.springbootdemoproject.controller;
// Importing required classes
import com.amiya.springbootdemoproject.entity.Department;
import com.amiya.springbootdemoproject.service.DepartmentService;
import java.util.List;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
// Annotation
@RestController
// Class
public class DepartmentController {
// Annotation
@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 8: Main application class
Java
package com.amiya.springbootdemoproject;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class SpringBootDemoProjectApplication {
public static void main(String[] args) {
SpringApplication.run(SpringBootDemoProjectApplication.class, args);
}
}
Step 10: Run the application
Now run your application and let's test the endpoints in Postman and also refer to our H2 Database.
Testing the Endpoint in Postman
1. Create (POST)
Endpoint 1: POST - http://localhost:8082/departments/

2. Get All Departments
Endpoint 2: GET - http://localhost:8082/departments/

3. Update a Department (PUT)
Endpoint 3: PUT - http://localhost:8082/departments/1

4. Delete a Department (DELETE)
Endpoint 4: DELETE - http://localhost:8082/departments/1

H2 Database is as depicted in below media

Explore
Java Basics
OOP & Interfaces
Collections
Exception Handling
Java Advanced
Practice Java