
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Difference Between save and saveAndFlush in Spring Java
Save and SaveAndFlush both can be used for saving entities. They both are both belong to the Spring data library. Save may or may not write your changes to the DB straight away. When we call saveAndFlush system is enforcing the synchronization of your model state with the DB.
What is the save method?
The save method is used to store an entity in the database. It adds the entity to the transactional buffer, and when the transaction is committed, the data is saved. It then returns the stored entity.
Example
The following is an example of the save method in Java:
@Repository public interface UserRepository extends JpaRepository{} @Service public class UserService { @Autowired private UserRepository userRepository; public User saveUser(User user) { // Save entity to database return userRepository.save(user); } }
What is the saveAndFlush method?
The saveAndFlush method is similar to the save method, but it flushes the data during execution and forces the database to write changes to disk before the transaction commits. The data is stored immediately.
Example
The following is an example of saveAndFlush in Java:
@Repository public interface UserRepository extends JpaRepository{} @Service public class UserService { @Autowired private UserRepository userRepository; public User saveAndFlushUser(User user) { // Save entity and flush to database immediately return userRepository.saveAndFlush(user); } }
Difference between Save and saveAndFlush
The following table shows the difference between Save and saveAndFlush:
Sr. No. | Key | Save | SaveAndFlush |
---|---|---|---|
1 |
Repository |
It belongs to CrudRepository |
It belongs to JPARepository |
2 |
Data flush Strategy |
It doesn't flush data directly to a database until and unless we explicitly call flush and commit method. |
It's flush directly flush data to a database. |
3 |
Bulk Save |
CrudRepository provides bulk save method |
saveAndFlush method doesn't support the bulk operation |
4 |
Data Visibility after saving |
It doesn't flush data directly to a database, therefore, changes will not be visible outside the transaction unless we explicitly call commit() in this transaction. |
Changes will be visible outside the transaction also. |
5 |
Use Case |
We use this method when we don't need to use the saved changes at a later point in the same transaction. |
We use this method when we need to use the saved changes at a later point in the same transaction. |