Igor
Igor

Reputation: 658

How to track delete events with Spring Data JPA auditing and Envers?

In my audited entity I have last modified fields:

@LastModifiedBy
private String lastModifiedBy;

@LastModifiedDate
private OffsetDateTime lastModifiedDate;

But they doesn't change when entity is deleted.

As I understand, I need to customize org.springframework.data.jpa.domain.support.AuditingEntityListener and add @PreRemove there, but I don't understand how to implement this, because I always get the following error:

org.hibernate.InstantiationException: Could not instantiate managed bean directly

Is there any other options to track delete events and store updated fields to Envers audit table?

Upvotes: 9

Views: 3976

Answers (2)

Igor
Igor

Reputation: 658

I made this workaround:

public class CustomValidityAuditStrategy extends ValidityAuditStrategy {

    private final AuditorAware<String> auditorAware = ...;

    @Override
    public void perform(final Session session, final String entityName,
                        final AuditEntitiesConfiguration audEntitiesCfg,
                        final Serializable id, final Object data,
                        final Object revision) {
        if (data instanceof Map) {
            final Map dataToUpdate = (Map) data;
            dataToUpdate.put("lastModifiedBy", auditorAware.get());
            dataToUpdate.put("lastModifiedDate", OffsetDateTime.now());
        }
        super.perform(session, entityName, audEntitiesCfg, id, data, revision);
    }
}

Upvotes: 5

Ali
Ali

Reputation: 1295

Spring Data JPA auditing by itself doesn't capture delete events. Envers, however, can track entity deletions. Here's how to address this with and without customizing the AuditingEntityListener:

  1. Add a boolean flag named deleted (or similar) to your entity.
  2. Update your delete logic to set this flag to true instead of physically deleting the entity.
  3. Configure Envers to audit this deleted flag.

This approach allows Envers to track the deletion event and store the entity state before the flag was set.

Upvotes: 0

Related Questions