Entitymanager.flush() VS EntityManager.getTransaction().commit - What should I prefer?

In your first example, the changes to the data are reflected in database after encountering flush, but it is still in transaction.

But in second example, you are committing transaction immediately. Therefore the changes are made into the database & transaction also ends there.

Sometimes, flush may be useful to persist the data in between the ongoing transaction & then finally commit the changes afterwards. So you can also rollback the previous changes if there occurs some problem afterwards, like for batch insert/update.


You did read the javadoc for flush and commit and know that flush is only for use within a transaction? It flushes (but doesn't commit), whereas commit commits data (obviously). They are distinct; there is no "preference" to be had. The first example is wrong, and should result in an exception on calling flush (TransactionRequiredException)


Both of your code samples doesn't persist or merge the entity state to be written to DB.

I don't think it appropriate to compare EntityManager.flush() and EnityManager.EntityTransaction.commit().

flush() MUST be enclosed in a transaction context and you don't have to do it explicitly unless needed (in rare cases), when EntityTransaction.commit() does that for you.

Refer this link Is it necessary to call a flush() (JPA interface) in this situation?

Refer this link Question about flushing with JPA before a query is called for a scenario to use flush()