Search code examples
javaspring-boothibernateinterceptor

Hibernate EmptyInterceptor works, but not Interceptor


I have the following Hibernate Interceptor:

@Component
@RequiredArgsConstructor
public class CustomInterceptor extends EmptyInterceptor {
  private static final long serialVersionUID = 7228720290710296593L;

  @Override
  public boolean onSave(Object entity, Serializable id, Object[] state, String[] propertyNames, Type[] types) {
    // do some things

    return super.onSave(entity, id, state, propertyNames, types);
  }

  @Override
  public boolean onFlushDirty(Object entity, Serializable id, Object[] currentState, Object[] previousState, String[] propertyNames, Type[] types) {
    // do some things

    return super.onFlushDirty(entity, id, currentState, previousState, propertyNames, types);
  }

}

I'm trying to upgrade by implementing Interceptor instead of extending EmptyInterceptor, since it is deprecated. My new interceptor is the following:

@Component
@RequiredArgsConstructor
public class CustomInterceptor implements Interceptor, Serializable {

  private static final long serialVersionUID = 7228720290710296593L;

  @Override
  public boolean onSave(Object entity, Object id, Object[] state, String[] propertyNames, Type[] types) {
    // do some things
  }

  @Override
  public boolean onFlushDirty(Object entity, Object id, Object[] currentState, Object[] previousState, String[] propertyNames, Type[] types) {
    // do some things
  }

}

Basically, both interceptors do exactly the same operations. However, the first one works, while the second one doesn't. By work, I mean onSave and onFlushDirty get called when it is expected, while in the second example they simply won't be invoked. So, it should not have anything to do with the operations involved within them. Since EmptyInterceptor really does nothing, I don't know what is wrong with the implementation.

UPDATE 1

I've just found out that instead of entering my overriden methods, it is simply using Interceptor default onSave and onFlushDirty. How is that possible?

UPDATE 2

If I override deprecated methods onSave and onFlushDirty instead of the valid ones it works.


Solution

  • Found the solution. It seemed that the project was using more than one interceptor. For that purpose, a custom interceptor was handling the calls to this CustomInterceptor. This handler was extending EmptyInterceptor, which made it to call deprecated methods instead of the valid ones. Simply implementing Interceptor in this handler made it work.