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?
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.
The @Transactional annotation makes use of the attributes rollbackFor or rollbackForClassName to rollback the transactions, and the attributes noRollbackFor or noRollbackForClassName to avoid rollback on listed exceptions. The default rollback behavior in the declarative approach will rollback on runtime exceptions.
flush(); Flushing is the process of synchronizing the underlying persistent store with persistable state held in memory. It will update or insert into your tables in the running transaction, but it may not commit those changes.
When the propagation is MANDATORY, if there is an active transaction, then it will be used. If there isn't an active transaction, then Spring throws an exception: @Transactional(propagation = Propagation. MANDATORY) public void mandatoryExample(String user) { // ... }
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With