JPA's EntityManager
provides several methods to manage the persistence of an entity.
Two such methods are:
void flush()
// Synchronize the persistence context to the underlying database.
getTransaction().commit()
// Commit the current resource transaction, writing any unflushed changes to the database.
Both these methods save the given entity into the database but there is a subtle difference in their working.
flush can be used to save an entity immediately into the database.
So it can be called multiple times in a transaction to save the entity piece-by-piece.
getTransaction().commit() also flushes the data to the database but it also
marks the end of the current transaction.
So data written with flush() can still be rolled-back if the transaction is not yet complete.
But with getTransaction().commit(), data cannot be rolled back.
Got a thought to share or found a bug in the code? We'd love to hear from you: