Kirill
Kirill

Reputation: 6036

EntityManager. Does Flush() save data in database as Commit()?

I have already looked through a number of topics about entityManager.flush() method. In my practice I always have used persist() and commit() methods.

Also I have found that sometimes flush() automatically executes during select request to database and at this point it checks for example constraints of database so if persisted objects is wrong due to constraints during select an exception will be thrown.

Actually I would like to understand:

  1. When you do flush() method then does a persisted data become saved in database? So you don't need to do commit() after flush()?

  2. What is the advantages of using flush() instead of commit(), may be in some concrete cases?

Upvotes: 4

Views: 9066

Answers (1)

Kirill
Kirill

Reputation: 6036

Thanks to JB Nizet now there is some clearity about flush().

Here is some points:

  1. To save data in database permanently JPA needs to insert data using insert/update/delete statements and then commit this data. Committing a transaction is always necessary.
  2. Flush() method executes only insert/update/delete statements without commiting the data, so the transaction and data can be rolled back.
  3. When you do commit() JPA flushes data before the commit i.e. flush() method is executed.
  4. During flush() constraints in database are checked as it executes sql-statements and place data into database.
  5. When isolation level set at READ_COMMITTED data after executing flush() is not seen in other transactions as flush() doesn't commit data.

Upvotes: 7

Related Questions