How to optimize when we use JpaRepository<T,T>'s ...AndFlush() methods? For example, SampleJpaRepository.save() vs SampleJpaRepository.saveAndFlush()?
I understand that the ...AndFlush() methods tend to be used for:
- Immediate synchronization with the database/To ensure that the entity is persisted right away
- Ensure that subsequent operations (like CRUD) reflect the latest state of the database
I also understand that database synchronization (flushing) is triggered when we:
- Commit a transaction
- Manually flush using a `flush()` or `...AndFlush()` operation
- Execute a query **(not sure what type of query triggers this?)**
Further, I am aware that Spring tends to defer database synchronization (flushing) by batching multiple operations and waiting until absolutely necessary before it flushes, in order to reduce the number of database round trips.
So then how do we know when to saveAndFlush()?
For example, I see that CommandLineRunner methods usually ALWAYS perform .saveAndFlush(). Why? Is it because they lack a @Transactional service method to do the flushing for them?