Search code examples
javaspring-boothibernate-enversaudit-logging

Fetching all changes made by a user in hibernate envers


In hibernate envers, I can get all changes made to an entity by using the following piece of code:

AuditQuery aq = auditReader.createQuery().forRevisionsOfEntityWithChanges(DummyEntity.class, false);

But is there a way to get all the changes made by a particular user for all entities?

I'm using the following entity to store revision info:

@RevisionEntity(UserRevisionListener.class)
@Entity(name = "env_audit_envers_info")
public class AuditEnversInfo extends DefaultRevisionEntity {

    private static final long serialVersionUID = -7604731515258123883L;

    @Column(name = "user_id")
    private String userId;

    public String getUserId() {
        return userId;
    }

    public void setUserId(String userId) {
        this.userId = userId;
    }

}

And entries to this model will be added on every change using the following listener:

public class UserRevisionListener implements RevisionListener {

    @Override
    public void newRevision(Object revisionEntity) {
        AuditEnversInfo auditEnversInfo = (AuditEnversInfo) revisionEntity;
        Optional<Authentication> auth = Optional.ofNullable(SecurityContextHolder.getContext().getAuthentication());
        String username = auth.isPresent() ? auth.get().getName() : "anonymoususer@email.com";
        auditEnversInfo.setUserId(username);
    }

}

Solution

  • The AuditEntity#revisionProperty method is what you're looking for:

    List results = auditReader.createQuery()
      .forRevisionsOfEntityWithChanges( DummyEntity.class, false )
      .add( AuditEntity.revisionProperty( "userId" ).eq( userId ) )
      .getResultList();
    

    The #revisionProperty methods were added to allow users who extend or use custom revision entity instances in their audit domain model to be able to add restrictions / projections or to be able to sort the results based on fields on that model.