Calling flush() in @Transactional method in Spring Boot application
It should not save anything before you call em.commit()
or transaction ends. The best explanation I found is from here .Below the essential excerpt:
This operation will cause DML statements (insert/update/delete etc) to be executed to the database but the current transaction will not be committed. That means flush() will not make current changes visible to other EntityManager instances or other external database clients; that will only happen at the transaction commit. In other words flush() operation will only flush the current memory cache from EntityManager to the database session.
So the flush might raise some JPA exceptions but it would not actually be committed to database before transaction ends.
Related question: JPA flush vs commit
Related videos on Youtube
Cybex
Updated on September 16, 2022Comments
-
Cybex over 1 year
Is it possible that calling Hibernate flush() in the middle of @Transactional method will save incomplete results in the database? For example, is it possible that this function could save "John" to the database?
@Transactional public void tt() { Student s = new Student("John"); em.persist(s); em.flush(); // Perform some calculations that change some attributes of the instance s.setName("Jeff"); }
I tried it with H2 in-memory database and it didn't save incomplete transaction changes. But is it possible under certain conditions and maybe with another DB engine?
-
aBnormaLzWhy would it save incomplete changes? Thats why a transaction is a transaction. A transaciton can either be completed or not-completed, but not partially completed. If you want to implement a behavior such that you should use 2 separate transactions.
-
-
Cybex over 5 yearsThanks, this is what I was looking for.
-
user2992476 over 3 years@pirho But what if you are working with big transactions and you would need to show the "status" in somewhere?
-
pirho over 3 years@user2992476 not sure if I understand you but if you can split the data to insert/update like 1000 rows at time and call flush() in between? I am not sure how your question is related to flush() but maybe you would like to ask a new question with details?