CRUD methods help you create, read, update, and delete data easily in your app. They make working with databases simple and organized.
CRUD methods (save, findById, findAll, delete) in Spring Boot
Start learning this pattern below
Jump into concepts and practice - no test required
or
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Introduction
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
Spring Boot
repository.save(user);
Spring Boot
Optional<User> user = repository.findById(1L);Spring Boot
List<User> users = repository.findAll();
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> {}
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.
Practice
1. Which Spring Boot repository method is used to add a new entity or update an existing one in the database?
easy
Solution
Step 1: Understand the purpose of
Thesave()save()method is designed to add a new entity or update an existing one in the database.Step 2: Compare with other methods
findById()andfindAll()are for reading data, anddelete()is for removing data, so they do not add or update.Final Answer:
save()-> Option AQuick Check:
Add or update data =save()[OK]
Hint: Remember: save = add or update data [OK]
Common Mistakes:
- Confusing
save()withfindById() - Thinking
delete()adds data - Using
findAll()to save data
2. Which of the following is the correct syntax to find an entity by its ID using Spring Boot's repository?
easy
Solution
Step 1: Identify the method to find by ID
The methodfindById(id)is used to retrieve an entity by its ID.Step 2: Check syntax correctness
repository.findById(id);is the correct syntax. Other methods do not accept an ID to find an entity.Final Answer:
repository.findById(id); -> Option AQuick Check:
Find by ID syntax = repository.findById(id) [OK]
Hint: Use findById(id) to get one entity by its ID [OK]
Common Mistakes:
- Using save() to find an entity
- Passing ID to findAll(), which takes no parameters
- Using delete() to find data
3. Given the following code snippet, what will
allUsers.size() return if the database has 3 user records?List<User> allUsers = userRepository.findAll(); int count = allUsers.size();
medium
Solution
Step 1: Understand
ThefindAll()behaviorfindAll()method returns a list of all entities in the database.Step 2: Count the number of records returned
If the database has 3 user records,allUserswill contain 3 elements, soallUsers.size()returns 3.Final Answer:
3 -> Option BQuick Check:
findAll() returns all records count = 3 [OK]
Hint: findAll() returns all records as a list [OK]
Common Mistakes:
- Assuming findAll() returns null if no records
- Confusing size() with findById() result
- Thinking findAll() returns a single entity
4. What is wrong with this code snippet if it throws a compilation error?
Assuming
userRepository.delete(5);
Assuming
delete expects an entity object, not an ID.medium
Solution
Step 1: Understand
Thedeletemethod signaturedeletemethod expects an entity object, not just an ID.Step 2: Use correct method to delete by ID
To delete by ID, usedeleteById(id)method instead ofdelete(id).Final Answer:
You should usedeleteById(5)instead to delete by ID. -> Option DQuick Check:
Delete by ID = deleteById(id) [OK]
Hint: Use deleteById(id) to remove by ID, not delete(entity) [OK]
Common Mistakes:
- Passing ID to delete() instead of entity
- Assuming delete() accepts ID directly
- Using wrong data type for ID
5. You want to update a user's email in the database using Spring Boot. Which sequence of repository methods correctly achieves this?
// Assume userId and newEmail are given
Optional<User> userOpt = userRepository.findById(userId);
if (userOpt.isPresent()) {
User user = userOpt.get();
user.setEmail(newEmail);
// What next?
}hard
Solution
Step 1: Retrieve the user entity by ID
The code usesfindById(userId)to get the user object.Step 2: Update the user and save changes
After setting the new email, callingsave(user)updates the database record.Final Answer:
CalluserRepository.save(user);to update the user. -> Option CQuick Check:
Update data = findById + modify + save [OK]
Hint: Update entity fields then call save() to persist changes [OK]
Common Mistakes:
- Assuming changes auto-save without calling save()
- Deleting before saving to update
- Using findAll() to update a single record
