In Hibernate, I wonder which conditions trigger flushing when flushMode is AUTO? It may be complex (or "magic") but what are the basic conditions?
Thanks
The FlushMode defines when your persistence provider flushes new and changed entities to the database. Based on the JPA specification, it can either do that automatically before executing a query and before committing the transaction (FlushModeType. AUTO) or only before committing the transaction (FlushModeType.
Flushing the session forces Hibernate to synchronize the in-memory state of the Session with the database (i.e. to write changes to the database). By default, Hibernate will flush changes automatically for you: before some query executions. when a transaction is committed.
Automatic flushing is the default mode for a Hibernate Session.
When flush mode is FlushMode.AUTO
it will happen at following times:
The purpose of this mode is to avoid 'stale' state. Changes made to objects in memory may conflict with the results of the query. My understanding is that Hibernate will do a 'dirty-checking', compare original and current state of objects. If they are different and Hibernate thinks that this difference will expose you to stale data, it will try to push this state to database. It is possible because Hibernate knows what tables will be 'touched' by query and what tables it will need to update for current dirty state.
Take a look at this article:
Auto-flushing is quite intelligent in what to flush when, although some situations might be hard to detect. To improve performance, Hibernate will not simply always flush everything, but look at the tables in the database that the query touches and the data in-memory that should be stored in those tables. If there is no overlap, no data will be persisted. If an overlap is found, the whole session will be flushed, to ensure consistency.
You can also look at org.hibernate.event.def.DefaultAutoFlushEventListener.onAutoFlush
source code.
There are couple disadvantages of FlushMode.AUTO
:
Because of these disadvantages I prefer FlushMode.COMMIT
which gives you more control. In this mode Hibernate waits until you explicitly call Commit or Flush and only synchronizes in-memory state with database after that.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With