0

save() and saveAndFlush() in Spring Data JPA both can return Entity ID.

As far as I search save() method shouldn't be able to return any value until it called by flush() and commit(). But I can be able to get Entity ID with save() method just like saveAndFlush().

When I implement JpaRepository and call save() and saveAndFlush() methods I've got Entity IDs for both of them.

So my question is how is it possible? Is it because of the @Transacitonal of save() method? And if it is, is there really any difference between those two methods at this point?

Selim D.
  • 3
  • 1
  • you can also have a look here: [save vs saveAndFlush](https://stackoverflow.com/questions/21203875/difference-between-save-and-saveandflush-in-spring-data-jpa) . When calling save method it is not guaranteed that changes will be flushed to DB immediately saveAndFlush will execute changes against DB immediately – I.Yuldoshev Aug 08 '23 at 09:46
  • Thank you @I.Yuldoshev, that topic was very useful. Ralf's answer is kinda what I was looking for. – Selim D. Aug 08 '23 at 10:17

1 Answers1

2

The behavior of the save() method in Spring Data JPA is determined by the underlying JPA provider. In the case of Hibernate, which is the default JPA provider used by Spring Data JPA, the save() method does not immediately flush the changes to the database. Instead, the changes are queued up and flushed to the database when the transaction is committed or when a flush operation is explicitly called.

However, when using a database provider that supports returning the ID of the saved entity before the transaction is committed, such as MySQL with the AUTO_INCREMENT feature, the save() method can return the ID immediately.

  • Thank you @user264660, So if I use MySQL or similar DB with the AUTO_INCREMENT feature, Hibernate handle it in the background and return Entity ID without even using saveAndFlush(). But if I use another DB that does not support that behaviour, I need to call saveAndFlush() instead of save(), correct? And also save() method has Transactional annotation so I may be wrong about this but at the end of the day it will call flush() and commit(). At this point is there really any difference? – Selim D. Aug 08 '23 at 10:14
  • The saveAndFlush() method, forces the changes to be immediately flushed to the database, even if the transaction is not yet committed. This can be useful in certain cases where you need to ensure that the changes are immediately persisted to the database. @Transactional has different purpose altogether. It is basically for transaction management like commit, rollback. – Arun Pratap Singh Aug 08 '23 at 10:22
  • Thank you @user264660 Also [save vs saveAndFlush](https://stackoverflow.com/questions/21203875/difference-between-save-and-saveandflush-in-spring-data-jpa) in this link I.Yuldoshev shared before, mahdi's answer was what I was looking for exactly. – Selim D. Aug 08 '23 at 10:28