Get Original object before update in hibernate's entity listeners

2k views Asked by At

I am trying to implement an entitylistener that compares the original and the updated object in the @PreUpdate event. I tried to use the Jpa Repository to query the original object by Id from DB to compare it with the object received in the event. But it retrieves the same object (i guess it returns the object present in the session scope).

Is there a way to get the original object from the database in the entity listener?

1

There are 1 answers

0
Simon Martinelli On

JPA does not provide the old and new state in the EntityListener.

But you can use Hibernates interceptors:

public static class LoggingInterceptor extends EmptyInterceptor {
    @Override
    public boolean onFlushDirty(
        Object entity,
        Serializable id,
        Object[] currentState,
        Object[] previousState,
        String[] propertyNames,
        Type[] types) {
            LOGGER.debugv( "Entity {0}#{1} changed from {2} to {3}",
                entity.getClass().getSimpleName(),
                id,
                Arrays.toString( previousState ),
                Arrays.toString( currentState )
            );
            return super.onFlushDirty( entity, id, currentState,
                previousState, propertyNames, types
        );
    }
}

In this example you see that you the the current and the previous state as arrays that can be easily compared.

Please read the docs: https://docs.jboss.org/hibernate/orm/5.4/userguide/html_single/Hibernate_User_Guide.html#events