Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling flush() in @Transactional method in Spring Boot application

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?

like image 789
Cybex Avatar asked Jan 18 '19 16:01

Cybex


People also ask

What does flush do in Spring boot?

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.

What is the use of @transactional annotation in Spring boot?

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.

Does flush commit transaction?

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.

Is @transactional required in Spring boot?

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) { // ... }


Video Answer


1 Answers

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

like image 181
pirho Avatar answered Sep 30 '22 09:09

pirho