After some debugging, i found the reason for the multiple calls of onFlushDirty
:
As explained above, the flushmode in my application is set to AUTO. Before a query is executed within a transaction, Hibernate decides whether to flush dirty entities or not. Whatever the outcome of this decision is: the method onFlushDirty
in the HibernateInterceptor
is called for sure for every dirty entity in the session even if it is decided not to be flushed afterwards.
If an entity of type A is in dirty state in the session and a query for entity type B is executed within this session, Hibernate does not flush the dirty entity because it does not affect the table the query is using and so the flush is not needed.
If there are multiple queries executed within a session it can occur that the onFlushDirty method is called several times for the same dirty entity but it gets never really flushed to the database and remains dirty until the running transaction is committed.
Have a look at the Hibernate class DefaultAutoFlushEventListener
public void onAutoFlush(AutoFlushEvent event) throws HibernateException {
...
if ( flushIsReallyNeeded(event, source) ) {
log.trace("Need to execute flush");
...
}
else {
log.trace("Dont need to execute flush");
...
}
}