Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

Spring Boot – CrudRepository with Example

  • Last Updated : 22 Dec, 2021

Spring Boot is built on the top of the spring and contains all the features of spring. And is becoming a favorite of developers these days because of its rapid production-ready environment which enables the developers to directly focus on the logic instead of struggling with the configuration and setup. Spring Boot is a microservice-based framework and making a production-ready application in it takes very little time. Following are some of the features of Spring Boot:

  • It allows avoiding heavy configuration of XML which is present in spring
  • It provides easy maintenance and creation of REST endpoints
  • It includes embedded Tomcat-server
  • Deployment is very easy, war and jar files can be easily deployed in the tomcat server

For more information please refer to this article: Introduction to Spring Boot. In this article, we are going to discuss how to use CrudRepository to manage data in a Spring Boot application.


There is an interface available in Spring Boot named as CrudRepository that contains methods for CRUD operations. It provides generic Crud operation on a repository. It is defined in the package and It extends the Spring Data Repository interface. If someone wants to use CrudRepository in the spring boot application he/she has to create an interface and extend the CrudRepository interface. 


public interface CrudRepository<T, ID> extends Repository<T, ID>


  • T: Domain type that repository manages (Generally the Entity/Model class name)
  • ID: Type of the id of the entity that repository manages (Generally the wrapper class of your @Id that is created inside the Entity/Model class)


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

Now let us discuss some of the most important methods that are available inside the CrudRepository are given below as follows:

Method 1: save(): Saves a given entity. Use the returned instance for further operations as the save operation might have changed the entity instance completely.


 <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.

Method 2: findById(): Retrieves an entity by its id.


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.

Method 3: findAll(): Returns all instances of the type.


Iterable<T> findAll()

Return Type: All entities

Method 4: count(): Returns the number of entities available.


long count()

Return Type: the number of entities.

Method 5: deleteById(): Deletes the entity with the given id.


void deleteById(ID id)

Parameters: Id (must not be null)

Exception Thrown: IllegalArgumentException in case the given id is null.


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: Refer to this article How to Create a Spring Boot Project with IntelliJ IDEA and create a Spring Boot project. 

Step 2: Add the following dependency

  • Spring Web
  • H2 Database
  • Lombok
  • Spring Data JPA

Below is the complete code for the pom.xml file. Please check if you have missed something.


<?xml version="1.0" encoding="UTF-8"?>
        <relativePath/> <!-- lookup parent from repository -->
    <description>Demo project for Spring Boot</description>

Step 3: Create 4 packages and create some classes and interfaces inside these packages as seen in the below image

  • entity
  • repository
  • service
  • controller


  • Green Rounded Icon ‘I’ Buttons are Interface
  • Blue Rounded Icon ‘C’ Buttons are Classes

Step 4: Inside the entity package

Create a simple POJO class inside the file. Below is the code for the file


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;
public class Department {
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long departmentId;
    private String departmentName;
    private String departmentAddress;
    private String departmentCode;

Step 5: 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 Program to Illustrate File
// Importing package module to this code
package com.amiya.springbootdemoproject.repository;
// Importing required classes
import com.amiya.springbootdemoproject.entity.Department;
import org.springframework.stereotype.Repository;
// Annotation
// Class
public interface DepartmentRepository
    extends CrudRepository<Department, Long> {

Step 6: Inside the service package

Inside the package create one interface named as DepartmentService and one class named as DepartmentServiceImpl. Below is the code for the file.

Example 1-A


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 1-B 


// Below is the code for the file.
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;
public class DepartmentServiceImpl implements DepartmentService{
    private DepartmentRepository departmentRepository;
    // save operation
    public Department saveDepartment(Department department) {
    // read operation
    public List<Department> fetchDepartmentList() {
        return (List<Department>) departmentRepository.findAll();
    // update operation
    public Department updateDepartment(Department department, Long departmentId) {
        Department depDB = departmentRepository.findById(departmentId).get();
        if (Objects.nonNull(department.getDepartmentName()) && !"".equalsIgnoreCase(department.getDepartmentName())) {
        if (Objects.nonNull(department.getDepartmentAddress()) && !"".equalsIgnoreCase(department.getDepartmentAddress())) {
        if (Objects.nonNull(department.getDepartmentCode()) && !"".equalsIgnoreCase(department.getDepartmentCode())) {
    // delete operation
    public void deleteDepartmentById(Long departmentId) {

Step 7: Inside the controller package

Inside the package create one class named as DepartmentController.


// Java Program to Illustrate DepartmentController File
// 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
// Class
public class DepartmentController {
    // Annotation
    @Autowired private DepartmentService departmentService;
    // Save operation
    public Department saveDepartment(
        @Valid @RequestBody Department department)
        return departmentService.saveDepartment(department);
    // Read operation
    public List<Department> fetchDepartmentList()
        return departmentService.fetchDepartmentList();
    // Update operation
    public Department
    updateDepartment(@RequestBody Department department,
                     @PathVariable("id") Long departmentId)
        return departmentService.updateDepartment(
            department, departmentId);
    // Delete operation
    public String deleteDepartmentById(@PathVariable("id")
                                       Long departmentId)
        return "Deleted Successfully";

Step 8: Below is the code for the file

server.port = 8082

# H2 Database

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

H2 Database is as depicted in below media

My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!