The flush()
method causes Hibernate to flush the session. You can configure Hibernate to use flushing mode for the session by using setFlushMode()
method. To get the flush mode for the current session, you can use getFlushMode()
method. To check, whether session is dirty, you can use isDirty()
method. By default, Hibernate manages flushing of the sessions.
As stated in the documentation:
https://docs.jboss.org/hibernate/orm/5.2/userguide/html_single/chapters/flushing/Flushing.html
Flushing
Flushing is the process of synchronizing the state of the persistence context with the underlying database. The
EntityManager
and the HibernateSession
expose a set of methods, through which the application developer can change the persistent state of an entity.The persistence context acts as a transactional write-behind cache, queuing any entity state change. Like any write-behind cache, changes are first applied in-memory and synchronized with the database during flush time. The flush operation takes every entity state change and translates it to an
INSERT
,UPDATE
orDELETE
statement.The flushing strategy is given by the flushMode of the current running Hibernate Session. Although JPA defines only two flushing strategies (
AUTO
andCOMMIT
), Hibernate has a much broader spectrum of flush types:
ALWAYS
: Flushes the Session before every query;AUTO
: This is the default mode and it flushes the Session only if necessary;COMMIT
: The Session tries to delay the flush until the current Transaction is committed, although it might flush prematurely too;MANUAL
: The Session flushing is delegated to the application, which must callSession.flush()
explicitly in order to apply the persistence context changes.By default, Hibernate uses the
AUTO
flush mode which triggers a flush in the following circumstances:
- prior to committing a Transaction;
- prior to executing a JPQL/HQL query that overlaps with the queued entity actions;
- before executing any native SQL query that has no registered synchronization.