0
0
Spring Bootframework~5 mins

CRUD methods (save, findById, findAll, delete) in Spring Boot

Choose your learning style9 modes available
Introduction

CRUD methods help you create, read, update, and delete data easily in your app. They make working with databases simple and organized.

When you want to add new data to your database.
When you need to get data by its unique ID.
When you want to list all data entries.
When you want to remove data from the database.
Syntax
Spring Boot
save(entity) - saves or updates an entity in the database
findById(id) - finds an entity by its ID
findAll() - retrieves all entities
delete(entity) - deletes an entity from the database

These methods are usually part of Spring Data JPA repositories.

They handle database operations without writing SQL.

Examples
Saves a new user or updates an existing one.
Spring Boot
repository.save(user);
Finds a user with ID 1. Returns Optional to handle if user is missing.
Spring Boot
Optional<User> user = repository.findById(1L);
Gets a list of all users in the database.
Spring Boot
List<User> users = repository.findAll();
Deletes the given user from the database.
Spring Boot
repository.delete(user);
Sample Program

This Spring Boot app shows how to use CRUD methods with a User entity. It saves a user, finds it by ID, lists all users, and deletes the user.

Spring Boot
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import jakarta.persistence.Entity;
import jakarta.persistence.Id;
import java.util.List;
import java.util.Optional;

@SpringBootApplication
public class CrudDemoApplication {
    public static void main(String[] args) {
        var context = SpringApplication.run(CrudDemoApplication.class, args);
        UserRepository repository = context.getBean(UserRepository.class);

        // Create and save a new user
        User user = new User(1L, "Alice");
        repository.save(user);

        // Find user by ID
        Optional<User> foundUser = repository.findById(1L);
        System.out.println("Found user: " + foundUser.orElse(null));

        // Find all users
        List<User> allUsers = repository.findAll();
        System.out.println("All users: " + allUsers);

        // Delete user
        repository.delete(user);
        System.out.println("User deleted.");
    }
}

@Entity
record User(@Id Long id, String name) {}

@Repository
interface UserRepository extends JpaRepository<User, Long> {}
OutputSuccess
Important Notes

Use Optional from findById to safely handle missing data.

Spring Data JPA automatically implements these methods for you.

Deleting an entity removes it permanently from the database.

Summary

CRUD methods let you manage data easily in Spring Boot.

Use save to add or update data.

Use findById, findAll, and delete to read and remove data.