What is the purpose of save() method in CrudRepository?

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.

Key Points: • If the entity's ID is null (or the entity is otherwise detected as new), save() performs an INSERT. • If the entity's ID already exists in the database, save() performs a merge, effectively an UPDATE. • save() returns the managed entity instance, which may differ from the one passed in (e.g. with a generated ID populated). • For bulk saves, saveAll() accepts an Iterable of entities and persists them in one call. • save() alone does not guarantee the change is flushed to the database immediately; that happens at transaction commit or an explicit flush.

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

Code Example:

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);

Interview Tip: 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."