15

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?

2
  • 1
    Why 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.
    – aBnormaLz
    Commented Jan 18, 2019 at 16:41
  • aBnormaLz, that's what I thought. But in one of the videos on Hibernate and Spring it was said that flush() forces entity manager to save these changes and that these changes will be rolled back if something fails in this method after a call to flush().
    – Cybex
    Commented Jan 18, 2019 at 17:10

1 Answer 1

21

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

4
  • Thanks, this is what I was looking for.
    – Cybex
    Commented Jan 18, 2019 at 17:47
  • @pirho But what if you are working with big transactions and you would need to show the "status" in somewhere? Commented Dec 8, 2020 at 8:30
  • @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?
    – pirho
    Commented Dec 8, 2020 at 12:14
  • @user2992476 I am facing the exact issue u have mentioned. stackoverflow.com/questions/74232316/… . Can you check out my question and share how you solved it?
    – Nagulan S
    Commented Oct 28, 2022 at 8:20

Not the answer you're looking for? Browse other questions tagged or ask your own question.