The save() method in CrudRepository persists an entity to the database, transparently handling both inserts and updates. Spring Data JPA decides which operation to perform based on whether the entity's identifier already exists in the database.
Calling userRepository.save(newUser) where newUser.getId() is null inserts a brand-new row and returns the entity with its generated primary key populated, while calling save() on an entity fetched earlier and then modified performs an update to the existing row instead.
public interface UserRepository extends CrudRepository<User, Long> {
}
// Insert
User newUser = new User("Alice");
User saved = userRepository.save(newUser); // saved.getId() now populated
// Update
User existing = userRepository.findById(1L).orElseThrow();
existing.setName("Alice Updated");
userRepository.save(existing);A concise interview answer is
save() in CrudRepository handles both insert and update -- if the entity's primary key is null or not found in the database it inserts a new row, and if it already exists it updates it. That means I use the same method call whether I'm creating a new record or persisting changes to an existing one.
Last updated: 16 July 2026
Previous question: How do you write a custom query in Spring Data JPA?
Next question: What is the use of @Modifying annotation?