2

In my audited entity i have 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 dont understand how to implement this, because i'm always have

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 ?

Naros
  • 19,928
  • 3
  • 41
  • 71
Igor
  • 478
  • 9
  • 22
  • 1
    Those annotations are spring-data-envers specific I do believe so hopefully someone from that community can provide a more flushed answer; however strictly from Envers perspective all we store is the current entity-state prior to removal. I believe the suggestion with `@PreRemove` is to alter that current entity-state in memory prior to the event listeners for auditing. That said, Envers does not store non-primary key attributes by default for deleted rows. There is a configuration option, `org.hibernate.envers.store_data_at_delete` which needs to be set to true to accomplish this. – Naros Nov 27 '19 at 14:44
  • @Naros i've posted my workaround, what do you think about it ? – Igor Nov 27 '19 at 15:39

1 Answers1

1

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);
}

}

Igor
  • 478
  • 9
  • 22
  • I believe you will want to only perform this if and only if the operation is a `DELETE`. As of now, this will modify the values of those two attributes regardless of which DML operation you perform, insert, update, or delete. I think it would probably be better to implement a custom `PreDeleteEventListener` where you take the entity state and manipulate it. This way you guarantee this runs _only_ on delete operations. – Naros Dec 02 '19 at 14:09