Skip to content
Tutorials Center
My learning

Topics

Lesson 56 of 119 ยท JPA and Hibernate

Auditing and Soft Deletes with Hibernate Envers

Track who changed what and when - Hibernate Envers @Audited revisions, AuditReader queries, Spring Data auditing with @CreatedDate and @CreatedBy, and soft deletes with @SQLDelete and @SoftDelete.

Sooner or later a business asks questions that your current table cannot answer. Who changed this customer's credit limit? What did the contract say last March? Who deleted that order, and can we get it back? Answering them means keeping history, and there are three common techniques in the JPA world: Hibernate Envers keeps a full revision history of entities, Spring Data auditing stamps each row with who created it and when it last changed, and soft deletes replace physical deletion with a flag.

In this lesson you will learn how each technique works and when to pick it. Hibernate and Spring Data are not on this course's code runner, so real annotated code is read-only. Both runnable examples use the H2 database and plain JDBC to build, in SQL, exactly the tables these tools generate, so you can see what Envers writes, how a past state is queried, and how a soft delete behaves.

Three kinds of "history"

Technique What you get Cost
Auditing columns (created_at, updated_by...) who/when for the latest change only nearly free
Envers revisions every historical version of every row, queryable by revision an extra audit table per entity and an extra insert per change
Soft delete deleted rows stay in the table and can be restored every query must exclude them; unique keys need care

They combine well: a typical enterprise entity has auditing columns and soft delete, and the most sensitive entities are also @Audited.

Hibernate Envers

Envers is a Hibernate module (org.hibernate.orm:hibernate-envers) that copies every change of an annotated entity into an audit table inside the same transaction. You add one annotation:

Java
import jakarta.persistence.*;
import org.hibernate.envers.Audited;

@Entity
@Audited                                  // all persistent fields are audited
public class Employee {
    @Id private int id;
    private String name;
    private String position;
    private int salary;

    @org.hibernate.envers.NotAudited      // exclude a field from history
    private String internalNote;
    // getters and setters
}

With schema generation on, Envers creates two kinds of tables:

  • REVINFO holds one row per revision: a number and a timestamp. A revision is one committed transaction that changed audited data, so all changes of one transaction share a revision number.
  • EMPLOYEE_AUD has the same columns as the entity plus REV (the revision) and REVTYPE (0 = added, 1 = modified, 2 = deleted). Its primary key is the entity id together with the revision.

If you generate the schema with Flyway (see Flyway migrations), you write these tables yourself. The program below does so and then plays the role of Envers: every change inserts a revision row and an audit row in the same transaction.

Java Revision tables, the way Envers writes them

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Read the output closely. Employee 1 has three audit rows even though the main table holds only the latest state. "As of revision 3" is answered by taking the newest audit row at or before that revision, which is how Envers resolves find(entity, id, revision). The deletion left an audit row with revtype = 2 and nothing else, so the last known state is found by looking one row back.

Reading history with AuditReader

In real code you ask an AuditReader, which is created from the EntityManager:

Java
import org.hibernate.envers.AuditReaderFactory;
import org.hibernate.envers.AuditReader;
import org.hibernate.envers.query.AuditEntity;

AuditReader reader = AuditReaderFactory.get(entityManager);

List<Number> revisions = reader.getRevisions(Employee.class, 1);          // [1, 3, 4]
Date when = reader.getRevisionDate(revisions.get(1));

Employee atRevisionThree = reader.find(Employee.class, 1, 3);             // the state at that revision

List<Employee> history = reader.createQuery()                             // every version of employee 1
    .forRevisionsOfEntity(Employee.class, true, false)
    .add(AuditEntity.id().eq(1))
    .getResultList();

List<Employee> highPaidThen = reader.createQuery()                        // a query "as of" revision 3
    .forEntitiesAtRevision(Employee.class, 3)
    .add(AuditEntity.property("salary").gt(3500))
    .getResultList();

List<Object[]> deleted = reader.createQuery()                             // who deleted what
    .forRevisionsOfEntity(Employee.class, false, true)
    .add(AuditEntity.revisionType().eq(RevisionType.DEL))
    .getResultList();

Entities returned from the reader are detached snapshots; changing them does nothing.

Recording who made the change

REVINFO only has a number and timestamp by default. To store the user, define your own revision entity and a listener that fills it:

Java
@Entity
@RevisionEntity(UserRevisionListener.class)
public class UserRevision extends DefaultRevisionEntity {
    private String changedBy;
    // getter and setter
}

public class UserRevisionListener implements RevisionListener {
    @Override
    public void newRevision(Object revisionEntity) {
        ((UserRevision) revisionEntity).setChangedBy(SecurityContextHolder.getContext().getAuthentication().getName());
    }
}

The listener is how the changed_by column in our example would be filled in a Spring Security application (see Spring Security).

Practical notes

  • Relationships. An audited entity with a reference to a non-audited entity needs @Audited(targetAuditMode = RelationTargetAuditMode.NOT_AUDITED), otherwise Envers expects the target to be audited too. Collections get their own link tables (for example ORDER_LINES_AUD).
  • Modified flags. @Audited(withModifiedFlag = true) adds a boolean column per property so you can ask "when did the salary change?" without comparing versions.
  • Schema changes. Every column you add to the entity must also be added to the _AUD table, so migrations touch two tables.
  • Cost. Each audited change is an extra insert, and audit tables grow without bound. Index (id, rev) and plan retention. Bulk JPQL updates and deletes bypass Envers because it listens to entity events, so history is missing for changes made through them.
  • Spring Data Envers adds RevisionRepository: extend it and call findRevisions(id), findLastChangeRevision(id) or findRevision(id, number) without touching AuditReader.

Spring Data auditing: who and when

When you only need the latest creator and modifier, skip Envers and let Spring Data fill columns for you. Enable it once, supply an AuditorAware, and put the fields in a base class:

Java
@Configuration
@EnableJpaAuditing
class AuditConfig {
    @Bean
    AuditorAware<String> auditor() {
        return () -> Optional.ofNullable(SecurityContextHolder.getContext().getAuthentication())
                             .map(Authentication::getName);
    }
}

@MappedSuperclass
@EntityListeners(AuditingEntityListener.class)
public abstract class AuditedEntity {
    @CreatedDate     @Column(updatable = false) private Instant createdAt;
    @LastModifiedDate                           private Instant updatedAt;
    @CreatedBy       @Column(updatable = false) private String createdBy;
    @LastModifiedBy                             private String updatedBy;
}

@Entity
public class Invoice extends AuditedEntity { ... }

Every persist sets createdAt/By, and every update changes updatedAt/By. Pair it with a @Version column for optimistic locking so concurrent edits are detected, as described in entity lifecycle and transactions. The simulated clock in the next example plays the role of the @CreatedDate and @LastModifiedDate listener.

Soft deletes

A soft delete keeps the row and marks it as deleted. People choose it to allow undo, keep foreign keys valid for old orders, or satisfy a retention rule. In Hibernate there are two ways.

The classic way rewrites two SQL statements:

Java
@Entity
@SQLDelete(sql = "UPDATE app_user SET deleted_at = ? WHERE id = ?")   // repository.delete() runs this
@SQLRestriction("deleted_at = 0")                                       // added to every query on this entity
public class AppUser { ... }

(@SQLRestriction replaced the older @Where, which is deprecated.) Since Hibernate 6.4 there is a dedicated annotation that does both with less ceremony:

Java
@Entity
@SoftDelete(columnName = "deleted", strategy = SoftDeleteType.DELETED)   // boolean column; ACTIVE and TIMESTAMP are alternatives
public class AppUser { ... }

The @Filter / @FilterDef mechanism is a third option when you want to switch the restriction on and off per session, for example to show deleted rows in an admin screen.

The program below mimics the SQL these annotations produce: the delete helper is @SQLDelete, and a view with WHERE deleted_at = 0 is the @SQLRestriction. It also demonstrates the most common soft-delete bug.

Java Soft delete: the rewritten SQL and the unique key trap

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The second registration of [email protected] fails while the first account is alive, which is correct. After the soft delete, a new account is allowed, but only because the unique key is (email, deleted_at) rather than email alone. With a plain unique constraint on email, the dead row would block that address forever. Databases offer partial indexes (WHERE deleted_at IS NULL, PostgreSQL) for the same purpose.

Soft delete pitfalls

  • Native queries and bulk JPQL do not always apply the restriction; test them. Anything that reads the table directly (reports, other services) must learn the rule too.
  • Cascades. Deleting a parent softly does not delete its children. Decide whether children get flagged too, or whether the restriction should hide them through the join.
  • Foreign keys and uniqueness need the design shown above.
  • Privacy. A soft-deleted person is still stored. Privacy laws such as GDPR may require real deletion or anonymization after a period, so schedule a purge job (see scheduling).
  • Size. Tables only grow. Archive old rows or partition by deletion date.

A common compromise: soft delete for user-driven undo, plus Envers on the entities where you must prove who removed what.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does one row of the REVINFO table represent in Envers?

    A revision groups all audited changes of one transaction. The _AUD tables refer to it with the REV column.
  2. 2. What does REVTYPE = 2 in an audit table mean?

    0 is ADD, 1 is MOD and 2 is DEL. A deletion audit row stores the id and little else.
  3. 3. Why can bulk JPQL updates leave gaps in Envers history?

    Bulk statements run directly in the database without loading entities, so no persistence events fire for Envers to react to.
  4. 4. Which Spring Data annotation fills in the user who first saved an entity?

    @CreatedBy is filled from AuditorAware when the entity is first persisted. @LastModifiedDate stores a time, @Version supports optimistic locking.
  5. 5. Why can a plain UNIQUE (email) constraint break soft deletes?

    The old row stays in the table. Include the deletion marker in the unique key, or use a partial unique index limited to live rows.

Summary

  • Envers (@Audited) writes every change into <table>_AUD plus a shared REVINFO revision row inside the same transaction; REVTYPE is 0, 1 or 2 for add, modify, delete.
  • AuditReader finds revisions, loads an entity as of a revision, and queries history; a custom @RevisionEntity records the user.
  • Bulk JPQL changes bypass Envers, audit tables grow forever, and every schema change touches two tables.
  • Spring Data auditing (@CreatedDate, @LastModifiedDate, @CreatedBy, @LastModifiedBy, AuditorAware) stamps who and when for the latest change only.
  • Soft delete uses @SQLDelete with @SQLRestriction, or Hibernate's @SoftDelete; design unique keys, cascades, native queries and privacy purges deliberately.

Next: JNDI and JMX Management looks at two older Java standards for naming and for monitoring a running application.