In Spring Data Jpa save() method allows us to save an entity to the DB. It belongs to the CrudRepository interface defined by Spring Data.
When we use the save() method, the data associated with the save operation will not be flushed to the DB unless and until an explicit call to flush() or commit() method is made.
As an example, let's create an Entity and JPA repository.
@Data
@Entity
public class User{
@Id
private Long id;
private String name;
}
public interface UserRepository extends JpaRepository<User, Long> {
}
Then can be used save() method like this,
userRepository.save(new User(1L, "Geeth"));
But saveAndFlush() method unlike save(). The saveAndFlush() method flushes the data immediately during the execution. This method belongs to the JpaRepository interface of Spring Data JPA. you can use it as follows.
userRepository.saveAndFlush(new User(2L, "Sam"));
Normally, we use this method when our business logic needs to read the saved changes at a later point during the same transaction but before the commit.
For instance, imagine a scenario where we have to execute a stored procedure that expects a property of the entity, which we're going to save. In this case, the save() method won't work since the changes are not in sync with the DB and the stored procedure doesn't know about the changes. The saveAndFlush() method is perfectly suited for this kind of scenario.