Search code examples
spring-datahibernate-envers

Spring Data Envers custom metadata


I have marked my entity @Audited and I can see that it logs the revision number and timestamp of a new revision, but how can I add custom metadata? I believe it must be possible since org.springframework.data.RevisionMetadata has the getDelegate() method with the following Javadoc:

Returns the underlying revision metadata which might provider more detailed implementation specific information.


Solution

  • From a pure Hibernate Envers perspective, if you want your revision entity to store additional context information about a revision such as who modified the entities or perhaps a reason for the change, then you would want to do this through a RevisionListener callback combined with a custom extension to DefaultRevisionEntity.

    For example:

    @Entity
    @RevisionEntity(CustomRevisionListener.class)
    public class CustomRevisionEntity extends DefaultRevisionEntity {
      private String userName;
      /* getter/setters */
    }
    
    public class CustomRevisionListener implements RevisionListener {
      @Override
      public void newRevision(Object revisionEntity) {
         CustomRevisionEntity cre = (CustomRevisionEntity)revisionEntity;
         cre.setUserName( UserContextHolder.getUserContext().getUserName() );
      }
    }
    

    Envers will detect the special annotated @RevisionEntity entity-class and use it. It will also detect the specified RevisionListener implementation and will instantiate and callback to this class when a new revision entity is constructed.

    Unfortunately, I can't speak for how this translates usage-wise with respect towardspring-data and spring-data-envers projects.