How can I tell if current session is dirty?

Viewed 656

I want to publish an event if and only if there were changes to the DB. I'm running under @Transaction is Spring context and I come up with this check:

    Session session = entityManager.unwrap(Session.class);
    session.isDirty();

That seems to fail for new (Transient) objects:

@Transactional
public Entity save(Entity newEntity) {
    Entity entity = entityRepository.save(newEntity);
    Session session = entityManager.unwrap(Session.class);
    session.isDirty(); // <-- returns `false` ):
    return entity;
}

Based on the answer here https://stackoverflow.com/a/5268617/672689 I would expect it to work and return true.

What am I missing?

UPDATE
Considering @fladdimir answer, although this function is called in a transaction context, I did add the @Transactional (from org.springframework.transaction.annotation) on the function. but I still encounter the same behaviour. The isDirty is returning false.

Moreover, as expected, the new entity doesn't shows on the DB while the program is hold on breakpoint at the line of the session.isDirty().

UPDATE_2
I also tried to change the session flush modes before calling the repo save, also without any effect:

    session.setFlushMode(FlushModeType.COMMIT);
    session.setHibernateFlushMode(FlushMode.MANUAL);
3 Answers

First of all, Session.isDirty() has a different meaning than what I understood. It tells if the current session is holding in memory queries which still haven't been sent to the DB. While I thought it tells if the transaction have changing queries. When saving a new entity, even in transaction, the insert query must be sent to the DB in order to get the new entity id, therefore the isDirty() will always be false after it.

So I ended up creating a class to extend SessionImpl and hold the change status for the session, updating it on persist and merge calls (the functions hibernate is using)

So this is the class I wrote:

import org.hibernate.HibernateException;
import org.hibernate.internal.SessionCreationOptions;
import org.hibernate.internal.SessionFactoryImpl;
import org.hibernate.internal.SessionImpl;

public class CustomSession extends SessionImpl {

    private boolean changed;

    public CustomSession(SessionFactoryImpl factory, SessionCreationOptions options) {
        super(factory, options);
        changed = false;
    }

    @Override
    public void persist(Object object) throws HibernateException {
        super.persist(object);
        changed = true;
    }

    @Override
    public void flush() throws HibernateException {
        changed = changed || isDirty();
        super.flush();        
    }

    public boolean isChanged() {
        return changed || isDirty();
    }
}

In order to use it I had to:

  • extend SessionFactoryImpl.SessionBuilderImpl to override the openSession function and return my CustomSession
  • extend SessionFactoryImpl to override the withOptions function to return the extended SessionFactoryImpl.SessionBuilderImpl
  • extend AbstractDelegatingSessionFactoryBuilderImplementor to override the build function to return the extended SessionFactoryImpl
  • implement SessionFactoryBuilderFactory to implement getSessionFactoryBuilder to return the extended AbstractDelegatingSessionFactoryBuilderImplementor
  • add org.hibernate.boot.spi.SessionFactoryBuilderFactory file under META-INF/services with value of my SessionFactoryBuilderFactory implementation full class name (for the spring to be aware of it).

UPDATE
There was a bug with capturing the "merge" calls (as tremendous7 comment), so I end up capturing the isDirty state before any flush, and also checking it once more when checking isChanged()

The following is a different way you might be able to leverage to track dirtiness.

Though architecturally different than your sample code, it may be more to the point of your actual goal (I want to publish an event if and only if there were changes to the DB).

Maybe you could use an Interceptor listener to let the entity manager do the heavy lifting and just TELL you what's dirty. Then you only have to react to it, instead of prod it to sort out what's dirty in the first place.

Take a look at this article: https://www.baeldung.com/hibernate-entity-lifecycle

It has a lot of test cases that basically check for dirtiness of objects being saved in various contexts and then it relies on a piece of code called the DirtyDataInspector that effectively listens to any items that are flagged dirty on flush and then just remembers them (i.e. keeps them in a list) so the unit test cases can assert that the things that SHOULD have been dirty were actually flushed as dirty.

The dirty data inspector code is on their github. Here's the direct link for ease of access.

Here is the code where the interceptor is applied to the factory so it can be effective. You might need to write this up in your injection framework accordingly.

The code for the Interceptor it is based on has a TON of lifecycle methods you can probably exploit to get the perfect behavior for "do this if there was actually a dirty save that occured".

You can see the full docs of it here.

We do not know your complete setup, but as @Christian Beikov suggested in the comment, is it possible that the insertion was already flushed before you call isDirty()?

This would happen when you called repository.save(newEntity) without a running transaction, since the SimpleJpaRepository's save method is annotated itself with @Transactional:

    @Transactional
    @Override
    public <S extends T> S save(S entity) {
        ...
    }

This will wrap the call in a new transaction if none is already active, and flush the insertion to the DB at the end of the transaction just before the method returns.

You might choose to annotate the method where you call save and isDirty with @Transactional, so that the transaction is created when your method is called, and propagated to the repository call. This way the transaction would not be committed when the save returns, and the session would still be dirty.


(edit, just for completeness: in case of using an identity ID generation strategy, the insertion of newly created entity is flushed during a repository's save call to generate the ID, before the running transaction is committed)

Related