Search code examples
springhibernatespring-data-jpahibernate-envers

Hibernate Envers: How to capture who deleted an entity in audit table


I am using hibernate-envers with spring. Everything works just fine, except when I delete an entity, it does not change the values of updated_by and updated_date inside audit table, instead it saves an entity exactly as it was before (just copy) after spring.jpa.properties.org.hibernate.envers.store_data_at_delete=true.

I have already tried to register listener EventType.PRE_DELETE, but it didn't help.

Here is my UpdateEntity:

@LastModifiedBy
@Column(nullable = false)
private Long updatedBy;

@LastModifiedDate
@Column(nullable = false)
private Date updatedDate;

How can I capture who deleted and when was deleted inside audit table by modifying columns updated_by and updated_date?


Solution

  • Looks like you are combining to features: Auditing support and Envers.

    Envers records every change to your entity including the delete if configured as you did.

    Auditing support traces update and insert timestamps and users. It doesn't work for deletes since there would be nowhere to store that information.

    If you want to keep the combination and still make it work you'd need to modify the entity (e.g. setting an extra flag deleting to true), flush it, maybe even commit it (I'm not sure if that is necessary) and then delete it.

    Probably a better approach is using a custom revision object and store the required data there as described in this question and answer: Ways to pass additional data to Custom RevisionEntity in Hibernate Envers?